我有一个包含许多单词的文本文件(每行一个单词)。我必须读入每个单词,修改单词,然后检查修改后的单词是否与文件中的任何单词匹配。我在最后一部分遇到了问题(这是我代码中的hasMatch方法)。这听起来很简单,我知道我应该做什么,但无论我尝试什么都行不通。你知道吗
#read in textfile
myFile = open('good_words.txt')
#function to remove first and last character in string, and reverse string
def modifyString(str):
rmFirstLast = str[1:len(str)-2] #slicing first and last char
reverseStr = rmFirstLast[::-1] #reverse string
return reverseStr
#go through list of words to determine if any string match modified string
def hasMatch(modifiedStr):
for line in myFile:
if line == modifiedStr:
print(modifiedStr + " found")
else:
print(modifiedStr + "not found")
for line in myFile:
word = str(line) #save string in line to a variable
#only modify strings that are greater than length 3
if len(word) >= 4:
#global modifiedStr #make variable global
modifiedStr = modifyString(word) #do string modification
hasMatch(modifiedStr)
myFile.close()
在您的代码中,您不只是分割第一个和最后一个字符,而是分割第一个和最后两个字符。你知道吗
改为:
这里有几个问题
set
而不是list
加快搜索速度str[1:-1]
做到了(感谢那些评论我答案的人)代码:
我在一个普通英语单词列表上测试了这个程序,得到了以下匹配结果:
Edit:另一个版本,它删除
set
并在排序列表上使用bisect
,以避免散列/散列冲突。你知道吗相关问题 更多 >
编程相关推荐