为什么"for letter in line"有效,而如果"word=line.strip()","for letter in word"不起作用。字符串搜索**在文件中**



目标是引入某个str输入,这些输入具有不同单词的相同字母。虽然我已经缩小了准确率。我无法找出一些问题。

文件链接 : http://www.gutenberg.org/files/3201/files/

fln=open('CROSSWD.TXT')
def uses_only(allow,word1,count,count_2):
y=0 #I've tried assigning line before loop as line=fln.readlines() does'nt work
for line in fln:
word=line.strip() # somehow the line is stripped of white spaces here or there
for letter in line: # Does'nt work for in word
x=count
z=count_2
if letter in allow:
count+=1
elif letter not in allow: # break loop for unwanted letters
count=0
count_2+=1
break

if x==len(word) and len(allow)==len(word): # runs if the letters match
y+=x/len(word)
word1+=word+','
return True,word1,int(y) #returns matching words & word count
def run():
allow=input('Enter the only letters the word must contain : ') # input from user         
word1=''
count=0
count_2=0
print(uses_only(allow,word1,count,count_2))          
run()

我面临的主要问题是

for letter in line:

如果我使用

for letter in word: **# What's making the loop to break?**

它返回一个空字符串,虽然他们应该在

word=line.strip()

也请帮助我使比赛更准确

输入 : 吃

电流输出 :

(True, 'ate,eat,eta,tae,tat,tea,tee,', 7)

输出给出具有匹配str的单词作为相同长度的输入和匹配的单词的编号。

调试代码 我意识到错误在于使用"word"变量 x 和 z 在最后一个循环中没有更新,只需将它们放在 for 循环的末尾:

for letter in word:  # Now work for in word
if letter in allow:
count+=1
elif letter not in allow: # break loop for unwanted letters
count=0
count_2+=1
break
x=count
z=count_2

为了克服这个问题,我将for letter in word放入一个单独的函数中。这既解决了迭代问题,又解决了字符串匹配的准确性。

fln=open('CROSSWD.TXT')
def test_word(word,allow): # Test for a sinlgle word in a line
for letter in word:
if letter not in allow:
return False
return True
def use_only():
count=0
allow=input('Enter the letters: ')
word1=''
for line in fln: # iteration for no. of loops
word=line.strip()
if test_word(word,allow)==True: #verify the match
word1+=word+','
count+=1
return word1, count
use_only()

在 :letter

出 :('eel,el,ell,er,ere,err,et,lee,leer,leet,let,letter,letterer,re,ree,reel,reeler,relet,reletter,ret,rete,retell,tee,teeter,tele,tell,teller,terete,terret,tetter,tree,tret,', 32)

最新更新