简体   繁体   English

如何在每行中拆分单词?

[英]How to split words in each line?

I wrote a code to get each word in a line of a text file.我编写了一个代码来获取文本文件一行中的每个单词。 Please see below.请参阅下文。

fname = input('Enter your file name:')
try:
    fhand = open(fname)
except:
    print('File cannot be opened:', fname)
word=[]
for word in fhand:
    word = word.split()
    print(word)

I run this code and I got what I want it.我运行这段代码,得到了我想要的。 But, when I just run print(word) , it only shows words of the last line.但是,当我只运行print(word) ,它只显示最后一行的单词。 I think I didn't define word in the beginning.我想我一开始没有定义word Then I added word = [] but the results are the same.然后我添加了word = []但结果是一样的。

在此处输入图片说明

in your loop -在你的循环中 -

for word in fhand:

you reassign the variable 'word' everytime it loops.每次循环时都重新分配变量“单词”。 Since you made 'word' a list, you would need to append to it the new lines instead of reassigning it.由于您将 'word' 设为列表,因此您需要向其添加新行而不是重新分配它。 Also, there is probably some issue with using 'word' twice, once as a list and once in your for loop counter.此外,使用 'word' 两次可能存在一些问题,一次作为列表,一次在 for 循环计数器中。 Try something like-尝试类似 -

word = []
fname = input('Enter your file name:')
with open(fname, 'r') as file:
   for line in file:
       word.append(line.split())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM