[英]Issues when grabbing words of a specific length from a txt file in python
我对我的代码的主要困惑是我的目标是在 dictionary.txt 中找到所有单词,特定长度只包含一个元音(定义为 a、e、i、o 和 u),没有其中的一个特定字母。 但是,它不能正常工作。 例如,如果我要查找所有长度为 9 且仅包含一个没有字母 't' 的元音的单词,下面的程序会告诉我“没有符合此条件的单词”。 但是文件中应该有两个词满足上述条件:“lynchings”和“lynchpins”。
我的字典位于https://filebin.net/96k7kso4i6nxcd2n/dictionary.txt?t=x9ujn62v
def onevowel(file):
length = int(input("Please enter the word length you are looking for: "))
letter = input("Please enter the letter you'd like to exclude: ")
wordnum = 0
for word in file:
word = word.strip()
if len(word) == length:
count = 0
for char in word:
if (char=='a' and char=='e' and char=='i' and char=='o' and char=='u'):
count += 1
if count == 1:
flag = 1
word_str = ""
for char in word:
if char == letter:
flag = 0
else:
word_str += char
if flag == 1:
print (word_str)
wordnum += 1
if wordnum == 0:
print ("There are no words that fit this criteria.")
if __name__ == "__main__":
my_file = open("dictionary.txt","r")
onevowel(my_file)
my_file.close()
用char in "aeoui"
替换char=='a' and char=='e' and char=='i' and char=='o' and char=='u'
(这永远不是真的)。
因为您只需要一个元音,请在此行中使用or
条件而不是and
:
if (char=='a' and char=='e' and char=='i' and char=='o' and char=='u'):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.