【发布时间】:2016-09-17 16:34:59
【问题描述】:
你好我最近一直在尝试在 Python 3 中创建一个程序,它将读取一个包含 23005 个单词的文本文件,然后用户将输入一个 9 个字符的字符串,程序将使用它来创建单词并将它们与文本文件中的单词进行比较。
我想打印包含 4-9 个字母并且还包含列表中间的字母的单词。例如,如果用户输入字符串“anitsksem”,那么第五个字母“s”必须出现在单词中。
这是我自己已经走了多远:
# Open selected file & read
filen = open("svenskaOrdUTF-8.txt", "r")
# Read all rows and store them in a list
wordList = filen.readlines()
# Close File
filen.close()
# letterList index
i = 0
# List of letters that user will input
letterList = []
# List of words that are our correct answers
solvedList = []
# User inputs 9 letters that will be stored in our letterList
string = input(str("Ange Nio Bokstäver: "))
userInput = False
# Checks if user input is correct
while userInput == False:
# if the string is equal to 9 letters
# insert letter into our letterList.
# also set userInput to True
if len(string) == 9:
userInput = True
for char in string:
letterList.insert(i, char)
i += 1
# If string not equal to 9 ask user for a new input
elif len(string) != 9:
print("Du har inte angivit nio bokstäver")
string = input(str("Ange Nio Bokstäver: "))
# For each word in wordList
# and for each char within that word
# check if said word contains a letter from our letterList
# if it does and meets the requirements to be a correct answer
# add said word to our solvedList
for word in wordList:
for char in word:
if char in letterList:
if len(word) >= 4 and len(word) <= 9 and letterList[4] in word:
print("Char:", word)
solvedList.append(word)
我遇到的问题是,它不是打印仅包含来自我的letterList 的字母的单词,而是打印出包含至少一个来自我的字母的单词我的letterList。这也意味着某些单词会被多次打印出来,例如,如果单词包含来自letterList 的多个字母。
我一直在尝试解决这些问题,但我似乎无法弄清楚。我还尝试使用排列来创建列表中所有可能的字母组合,然后将它们与我的wordlist 进行比较,但是我认为鉴于必须创建的组合数量,解决方案会变慢。
# For each word in wordList
# and for each char within that word
# check if said word contains a letter from our letterList
# if it does and meets the requirements to be a correct answer
# add said word to our solvedList
for word in wordList:
for char in word:
if char in letterList:
if len(word) >= 4 and len(word) <= 9 and letterList[4] in word:
print("Char:", word)
solvedList.append(word)
另外,由于我对 python 有点陌生,如果您有任何一般性提示要分享,我将不胜感激。
【问题讨论】:
标签: python python-3.x for-loop comparison iteration