如何在列表中的字符串中找到单词?(Python) [英] How to find a word in a string in a list? (Python)
本文介绍了如何在列表中的字符串中找到单词?(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我正在尝试寻找一种方法,以便我可以读取txt文件并找到特定的单词.我一直使用
So im trying to find a way so I can read a txt file and find a specific word. I have been calling the file with
myfile=open('daily.txt','r')
r=myfile.readlines()
这将返回一个列表,其中包含文件中每一行的字符串,我想在列表中的字符串之一中找到一个单词.
that would return a list with a string for each line in the file, i want to find a word in one of the strings inside the list.
对不起,我的意思是,如果有一种方法可以找到该单词在txt文件中的位置,例如 x = myfile [12]
x = x [2:6]
edit:
Im sorry I meant if there was a way to find where the word is in the txt file, like x=myfile[12]
x=x[2:6]
推荐答案
def findLines():
myWord = 'someWordIWantToSearchFor'
answer = []
with open('daily.txt') as myfile:
lines = myfile.readlines()
for line in lines:
if myWord in line:
answer.append(line)
return answer
这篇关于如何在列表中的字符串中找到单词?(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文