简体   繁体   English

如何在列表中分割字符串

[英]How to split strings in lists

I have a text in a file with multiple lines. 我在多行文件中有一个文本。 I would like to create one big list, with each line as a seperate list inside. 我想创建一个大列表,每行作为一个单独的列表放在里面。 Within these lists each word should be a string. 在这些列表中,每个单词应该是一个字符串。 This is my code at the moment, I am failling to split the strings within the lists. 这是我目前的代码,我无法在列表中拆分字符串。

f = open("test.txt","r")

for line in f.readlines():
line2= line.split(",")
print(line2)

f.close()

This is the output: 这是输出:

['Das ist 1e\n']
['Textdatei', '\n']
['bestehend aus mehreren Wörtern.']

You can do: 你可以做:

with open('file.txt') as f:
    out = [line.rstrip('\n').split(',') for line in f]

ie iterate over the lines of the file object (which is an iterator ), strip off the newline at the end and split the line on comma. 即遍历文件对象(它是一个迭代 )的线, strip离末尾的换行符和split上逗号行了。

Note that, if you want to strip off whitespaces from both start and end, use line.strip() instead. 请注意,如果要从开头和结尾剥离空格,请改用line.strip() Also, the file would be opened in rt (read-text) mode by default, so you can drop the explicit declaration of the mode parameter, if you want. 另外,默认情况下将在rt (读取文本)模式下打开文件,因此,如果需要,可以删除mode参数的显式声明。


Edit: 编辑:

It seems you have space separated words, in that case use split() : 看来您有用空格分隔的单词,在这种情况下,请使用split()

with open('file.txt') as f:
    out = [line.rstrip('\n').split() for line in f]

这是一线的。

[line.split(',') for line in Path('test.txt').open('r').read().split('\n')]

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

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