我写了一个函数,该函数应该将.txt
中的单词添加到list
,但它应该忽略空行,我的函数如何在空行输出['',]
。将单词添加到列表
def words(filename):
word = []
file = open(filename)
for line in file:
word.append(line.strip())
return word
我怎么能解决这个感谢
我写了一个函数,该函数应该将.txt
中的单词添加到list
,但它应该忽略空行,我的函数如何在空行输出['',]
。将单词添加到列表
def words(filename):
word = []
file = open(filename)
for line in file:
word.append(line.strip())
return word
我怎么能解决这个感谢
你需要测试一个空行,并跳过在这种情况下追加。
def words(filename):
word = []
file = open(filename)
for line in file:
line=line.strip()
if len(line):
word.append(line)
return word
yup感谢你发现 - 现在编辑它 – heroworkshop
此外,你可以做'if line:',如果len(line)'更简单也更高效,并且看到我对关于关闭文件的问题的评论。 –
怎么样一个简单的测试,如果?
def words(filename):
word = []
file = open(filename)
for line in file:
if line.strip() != ' ':
word.append(line.strip())
return word
编辑:我行 除了后忘了.strip(),你也可以使用if line.strip():
最后,如果你想获得一个单词列表,但每行有几个单词,你需要将它们分割。假设你的分隔符'“:
def words(filename):
word = []
file = open(filename)
for line in file:
if line.strip() != ' ':
word.extend(line.strip().split())
return word
除了你会不会考虑包含空白也为空线一条线吗?一个流浪“”字,你仍然会得到空条目OP在抱怨 – heroworkshop
@heroworkshop谢谢,我纠正我的答案。另外请注意,如果你想从句子中得到单词,你可能需要导入're'并找到正确的正则表达式(一定不要太复杂) – Wli
可以解决这个问题这样的:
def words(filename):
word = []
file = open(filename)
for line in file:
if not line.strip():
word.append(line)
return word
你的问题是,您要添加line.strip()
,但如果line
实际上是一个空字符串,会发生什么?看:
In [1]: line = ''
In [2]: line.strip()
Out[2]: ''
''.strip()
返回一个空字符串。
我认为OP想要追加剥离的线,而不是未剥离的线。 –
@ PM2Ring如果是这种情况,我相信OP能够改变为'word.append(line.strip()'。 – Maroun
关闭打开的文件是一种很好的做法。或者在'with'块中打开文件,以便它自动关闭。 –
我仍然在做这个工作,只是卡住在这个部分 – James