读取文件 - 匹配行与列表
Reading file - Match line with List
我正在读取一个 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)
有人知道我该怎么做吗?
您可以使用列表理解的替代方法:
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)
请查看差异,当您迭代 str
和 list
、
时
>>> 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
我正在读取一个 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)
有人知道我该怎么做吗?
您可以使用列表理解的替代方法:
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)
请查看差异,当您迭代 str
和 list
、
>>> 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