读取文件-与列表匹配行

时间:2019-04-01 13:40:26

标签: python pandas file sys

我正在使用Python读取文件,我只想提取与某些内容匹配的行。 '\ 我的问题是:如果我只传递一个字符串来进行比赛,我就能做到(就像下面的代码一样)'

import sys,os
import re
import pandas as pd

path = 'file'
sports = ['Sports', 'Nature']
keyword = 'Sports'
data = pd.DataFrame([])

with open(path) as auto:
  for line in auto:
    if keyword in line:
        print(line)

我传递了一个列表,但我无法检索到任何行:

with open(path) as auto:
  for line in auto:
    if any(x in errors for x in line):
        print(line)

有人知道我该怎么做吗?

2 个答案:

答案 0 :(得分:1)

当您遍历strlist时,请注意区别,

>>> keyword = ['sports', 'something else']
>>> line = "line that has a word sports in it"
>>> 'sports' in line
True
>>> any(x in keyword  for x in line.split()) # iterating over list
True
>>> any(x in keyword  for x in line) # iterating over each characters in an string
False

答案 1 :(得分:0)

您可以使用列表理解功能来替代:

file = [line.lower() for line in open(path).readlines()]
required_line = [line for text in keyword for line in file if text.lower() in line]

通过您的方法,您错过了任何东西:

with open(path) as auto:
    for line in auto:
        if any(x for x in keyword for x in line):
            print(lines)