所以我想要做的是创建一个dict:
当我运行我的程序时,我得到Ex。字:{(' w',' o',' r',' d')}不是字:dorw,wrdo,rowd。文本文件每行只包含很多单词。
代码:
def main():
wordList = readMatrix()
print(lengthWord())
def readMatrix():
wordList = []
strFile = open("words.txt", "r")
lines = strFile.readlines()
for line in lines:
word = sorted(line.rstrip().lower())
wordList.append(tuple(word))
return tuple(wordList)
def lengthWord():
lenWord = 4
sortDict = {}
wordList = readMatrix()
for word in wordList:
if len(word) == lenWord:
sortWord = ''.join(sorted(word))
if sortWord not in sortDict:
sortDict[sortWord] = set()
sortDict[sortWord].add(word)
return sortDict
main()
答案 0 :(得分:2)
您正在创建文件中每个单词的元组:
for line in lines:
word = sorted(line.rstrip().lower())
wordList.append(tuple(word))
这会对你的所有字谜进行排序,创建重复的排序字符元组。
如果你想跟踪所有可能的单词,你应该不在这里产生元组。请阅读以下文字:
for line in lines:
word = line.rstrip().lower()
wordList.append(word)
并使用lengthWord()
函数处理这些字词;此函数确实需要将wordList
值作为参数:
def lengthWord(wordList):
# ...
你需要从main()
传递它:
def main():
wordList = readMatrix()
print(lengthWord(wordList))