gpt4 book ai didi

python - 如何在txt文件中查找字符串

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:18 31 4
gpt4 key购买 nike

如何在文本文件中查找字符串或列表。如果我有一个仅包含单词、随机单词而不是句子的文本文件,我如何在其中找到一个字符串。假设我接受了用户输入,我该如何测试或检查用户输入的字符串是否存在于文本文件中。

到目前为止我有这个:

x = open('sample.txt')

for a in x:
b = a.split() #converts the string from the txt to a list

c = input('enter: ') #user input

if any(c in a for a in b):
print('yes')

想做一个简单的拼写检查器。所以我想从用户输入的字符串中检查该字符串是否与 txt 文件中的字符串/列表匹配

最佳答案

你的意思是,如何在这个文件中找到一个词?那是

with open("sample.txt") as input:
dictionary = set(input.read().split())

然后

w in dictionary

为你的话w

关于python - 如何在txt文件中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9193476/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com