我想解析一个文件,并删除其中没有单词“ Asia”的所有行。我也想忽略标题
Header record
India is in Asia
Japan is in Asia
Germany is in Europe
China is in Asia
US is in NortAmerica
Brazil is in SouthAmerica
Trailer record
有没有一种方法可以改善以下代码
fhand = open('P:\Python\Python.txt')
a=[]
for line in fhand:
a.append(line.split())
for i in a[1:-1]:
if 'Asia' not in i:
a.remove(i)
print (a[1:-1])
答案 0 :(得分:1)
标题似乎是下面没有VALID_MARKER的任何内容。因此,您可以如此进行迭代并以这种方式进行过滤:
with open('data.txt', 'r') as f:
data = f.readlines()
IGNORE_COUNTRY = 'Asia'
VALID_MARKER = 'is in'
cleaned_lines = []
for line in data:
if IGNORE_COUNTRY in line or VALID_MARKER not in line:
continue
cleaned_lines.append(line.rstrip())
print cleaned_lines
输出:
['Germany is in Europe', 'US is in NortAmerica', 'Brazil is in SouthAmerica']
答案 1 :(得分:0)
打开文件,使用readlines()
获取内容,然后仅选择所需的行:包含“是”,而不是“亚洲”:
clean = [line.strip() for line in open('P:\Python\Python.txt').readlines()
if "is in" in line and
"Asia" not in line]
print(clean)
输出:
[Germany is in Europe', 'US is in NortAmerica', 'Brazil is in SouthAmerica']
请注意,如果您要写入另一个文件,则列表推导可以直接放入write
命令中,并且该过程会折叠成一行。
此外,这在命令行中可能更容易。在UNIX(Linux)中,awk
和其他工具在这方面非常擅长。
答案 2 :(得分:0)
你只想忽略标题吗?拖车没问题?如果是这样:
from itertools import filterfalse
with open('data.txt') as file:
file.readline() # ignore header
for line in filterfalse(lambda line: 'Asia' in line, file):
print(line)