Python:如何扫描.txt并将特定单词拉出到列表中

问题描述 投票:1回答:3

我想逐行扫描.txt文件中的特定单词。找到单词后,我想将该特定行添加到列表中。任何帮助,将不胜感激!

下面的代码打印一个空列表......

list = [ ]
word = 'help!'

with open('help!') as f:
    lines = f.readlines()

if word in lines:
    list.append(word)

print(list)
python list text append
3个回答
2
投票

您可以迭代.txt文件中的所有行,并检查该行中是否出现该单词。如果是这样,请将该行附加到列表中。

list = [ ]
word = 'help!'

with open('text_file.txt') as f:
    lines = f.readlines()

for line in lines: #iterate over lines
    if word in line: #check if word in line
        list.append(line) #add line

print(list)

0
投票

你很可能想在每行的文件上做一个for循环,看看你的单词是否显示出来。

# declare variables
list = []
word = 'help!'

# filepath to your .txt file, if its in the
# same directory as your py script, then just set it as the .txt name
filePath = 'stackOverflow.txt'

# for each line in your .txt file
for line in open(filePath):
     # if your word is in that line then ... 
     if(word in line):
          # append to list
          list.append(line)

# print list
print(list)

希望这可以帮助! =)


0
投票

您可能需要小心使用以下方法检查单词的句子:

If (word in line):
    list.append(line)

如果word =“in”,则在“坐在板凳上”线上进行测试时,上述条件将返回误报“真”。

更好的方法可能是:

if (word in line.split(“ “)):
    list.append(line)

这将错过标点符号后面的单词,因此首先删除标点符号将是更好的解决方案。您可以导入re并使用正则表达式首先删除标点符号。

Regex = re.compile(r”\W+”)
if (word in Regex.sub(“ “,line).split(“ “)):
        list.append(line)
© www.soinside.com 2019 - 2024. All rights reserved.