我的文本文件和search.py文件位于同一文件夹中。
说我的文本文件中有10个项目(苹果,橙色,白色,粉红色,紫色,绿色,星期天,星期一,船,英语)。我希望我的代码列出所有包含字符的项目(以下代码中的“ a”)。
它对于第一个字符很好用,但是当我第二次尝试另一个字符时,它什么也没显示。
words=open("my_words.txt","r")
count=0
while True:
a=input("Enter a letter please :")
print("\n-----------------------")
for i in words:
if a in i:
count+=1
print(i)
print("\n-----------------------")
print("In this list we have", count," items that contain",a)
在我们的代码中,变量“ words”是一个缓冲区,只能使用一次来获取文件文本。
I AM ASSUMING THAT THE WORDS IN FILE ARE SEPARATED BY ','.
尝试这个:
words=open("my_words.txt","r").read().split(',')
count=0
while True:
a=input("Enter a letter please :")
print("\n-----------------------")
for i in words:
if a in i:
count+=1
print(i)
print("\n-----------------------")
print("In this list we have", count," items that contain",a)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句