问题描述
我正在编写一个程序,在其中给我一个名为words.txt的文件。它包含了每个单词,并以 “啊 啊啊 ah ah 啊 。 。 。” 使用该文件,我应该遍历该文件并查找具有三组双字母的所有单词。 (双字母是连续存在同一字母的两个字母,例如在引导,杀戮或深渊中。)三套双字母表示像委员会之类的单词,分别为(mm),2(tt)和(set)。第三套(ee)。然后,程序必须显示找到的所有单词,以及找到的单词总数。我不允许导入模块或其他工具,只能使用基本的Python。任何帮助表示赞赏。
found_words = []
total = 0
for line in f:
line = line.strip()
letter_list = []
for letter in line:
letter_list.append(letter)
for letter in line:
if letter_list[0] == letter_list[1]:
found_words.append(line)
else:
del letter_list[0]
print(letter_list)
print(found_words)
f.close()
解决方法
你在这里
f = open("words.txt")
found_words = []
words= f.read().split()
for word in words:
consecutive =0
lastLetter=""
for letter in word:
if letter == lastLetter:
consecutive+=1
//If you want it that if three similar letters should count as 2 repeated,dont uncomment the next line. If you dont want 3 consecutive letters to count as 2 repeated,uncomment the next line
//lastLetter=""
lastLetter =letter
if consecutive ==3:
found_words.append(word)
print("WORDS:",found_words)
print("LENGTH:",len(found_words))