Python – How to compare strings to ensure they do not contain a double character, then save them to a file
Question:
I am trying to make it so that if there are 2 words that have double letters in the loop, it will simply pass over them, or vice versa.
def initalizeData():
try:
words = open('words.txt', 'r')
except FileNotFoundError:
print("Check the file name or path.")
else:
list = open('final.txt', 'a')
scriptwords = words.readlines()
for w in scriptwords[:]:
if len(w) >= 3 and len(w) <= 6:
if w[:1] == 'a' or w[:1] == 'p':
for letter in scriptwords:
#this is where the statement should go, below is my attempt at it.
#if scriptwords[letter] != scriptwords[(letter+1)]:
list.write(w.upper())
list.close()
I have tried the above, and the result is that Replit says:
File "main.py", line 14, in initalizeData
if scriptwords[letter] != scriptwords[(letter+1)]:
TypeError: list indices must be integers or slices, not str
Answers:
You can iterate through the letters of the word using the pattern below. This will check that all pairs of letters are different in the word. And I also changed the file name to word_list
to avoid the name collision with list
.
def initalizeData():
try:
words = open('words.txt', 'r')
except FileNotFoundError:
print("Check the file name or path.")
else:
word_list = open('final.txt', 'a')
scriptwords = words.readlines()
for w in scriptwords:
if len(w) >= 3 and len(w) <= 6:
if w[:1] == 'a' or w[:1] == 'p':
if all(l1 != l2 for l1,l2 in zip(w,w[1:])):
word_list.write(w.upper())
word_list.close()
I am trying to make it so that if there are 2 words that have double letters in the loop, it will simply pass over them, or vice versa.
def initalizeData():
try:
words = open('words.txt', 'r')
except FileNotFoundError:
print("Check the file name or path.")
else:
list = open('final.txt', 'a')
scriptwords = words.readlines()
for w in scriptwords[:]:
if len(w) >= 3 and len(w) <= 6:
if w[:1] == 'a' or w[:1] == 'p':
for letter in scriptwords:
#this is where the statement should go, below is my attempt at it.
#if scriptwords[letter] != scriptwords[(letter+1)]:
list.write(w.upper())
list.close()
I have tried the above, and the result is that Replit says:
File "main.py", line 14, in initalizeData
if scriptwords[letter] != scriptwords[(letter+1)]:
TypeError: list indices must be integers or slices, not str
You can iterate through the letters of the word using the pattern below. This will check that all pairs of letters are different in the word. And I also changed the file name to word_list
to avoid the name collision with list
.
def initalizeData():
try:
words = open('words.txt', 'r')
except FileNotFoundError:
print("Check the file name or path.")
else:
word_list = open('final.txt', 'a')
scriptwords = words.readlines()
for w in scriptwords:
if len(w) >= 3 and len(w) <= 6:
if w[:1] == 'a' or w[:1] == 'p':
if all(l1 != l2 for l1,l2 in zip(w,w[1:])):
word_list.write(w.upper())
word_list.close()