我正在尝试打开一个包含两个句子的文件,并将这两个句子分成一个单词列表。但是,当我这样做时,我还得到一个额外的空列表,如何防止这种情况?
branch1
我明白了:
master
答案 0 :(得分:3)
使用splitlines()
将文件的所有行读入列表:
with open('filename.txt', 'r') as f:
mylist = f.read().splitlines()
使用此列表理解拆分行:
mylist = [line.split() for line in mylist]
使用filter()
删除所有空列表项:
mylist = filter(None, mylist)
您还可以在阅读文件时完成所有这些操作:
mylist = []
with open('filename.txt', 'r') as f:
for line in f:
if line.strip():
mylist.append(line.split())
答案 1 :(得分:1)
x1=[]
fopen=open("testxxx",'r')
for line in fopen:
x=line.split()
if x:
x1.append(x)
print x1
答案 2 :(得分:0)
删除空列表:
x1= [x for x in x1 if x]
答案 3 :(得分:0)
您可以使用readlines
:
with open('filename.txt', 'r') as f:
mylist = [line for line in f.readlines() if line.strip() != '']
或者:
with open('filename.txt', 'r') as f:
lines = []
for line in f.readlines():
if line.strip() != '':
lines.append(line)
或者:
with open('filename.txt', 'r') as f:
lines = filter(lambda x: x.strip() != '', f.readlines())
答案 4 :(得分:0)
您可以在尝试拆分其单词时检查读取行是否为空。
word_list = []
lines = []
with open('myfile.txt') as file:
# stripping the whitespaces as the blank line may contain whitespaces
lines = [line.strip() for line in file.readlines()]
# split to words those lines that are not empty strings
word_list = [line.split() for line in lines if line]
with open('myfile.txt') as file:
word_list = [line.split() for line in file.readlines() if line.strip()]
请注意,空字符串''
在python中是假的。因此,如果line
是空字符串,if line
的结果为{0},同样适用于line.strip()
。看一下python中的truth-value-testing。