繁体   English   中英

Python:多行文本文件读取为单行

[英]Python: multi-line text file reading as single line

我正在尝试读取包含由换行符分隔的单词的文本文件。 但是,我似乎无法让 PyCharm 识别换行符。 我已经尝试了一切,包括更改 Line Separator settings ,但它仍然将文本文件视为单行。 有什么解决办法吗?

inFile = open("words.txt", 'r')
wordList = []
for line in inFile:
    wordList.append(line.strip().lower())
len(wordList) # returns 1
inFile = open("words.txt", 'r')
inFile.readlines() # returns 1 line containing all words

文本文件: https://courses.edx.org/assets/courseware/v1/1e89542cc136bc1e496aac7130cac1ba/asset-v1:MITx+6.00.1x+2T2018+type@asset+block/Problem28404.ZADCDBD2Z918A

IDE:PyCharm 2018.2.4 在 macOS 上

谢谢

做这个:

with open("words.txt", "r") as file:
     words = file.read().split()

print(words)

你会得到:

['AA', 'AAH', 'AAHED', 'AAHING', ......]

如果想要一个巨大的字符串中的所有单词,只需避免使用split()方法:

with open("words.txt", "r") as file:
         words = file.read()

暂无
暂无

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

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