我有一个由数字和单词组成的文本文件,例如,像这样-09807754 18 n 03 aristocrat 0 blue_blood 0 patrician我想将其拆分,以便每个单词或数字都以新行出现。
09807754 18 n 03 aristocrat 0 blue_blood 0 patrician
空格分隔符将是理想的,因为我希望带有破折号的单词保持连接。
这是我到目前为止所拥有的:
f = open('words.txt', 'r') for word in f: print(word)
我不太确定如何从这里开始,我希望将其作为输出:
09807754 18 n 3 aristocrat ...
给定此文件:
$ cat words.txt line1 word1 word2 line2 word3 word4 line3 word5 word6
如果您一次只想要一个字(忽略文件中空格与换行符的含义):
with open('words.txt','r') as f: for line in f: for word in line.split(): print(word)
印刷品:
line1 word1 word2 line2 ... word6
同样,如果要将文件拼合为文件中单个单词的平面列表,则可以执行以下操作:
with open('words.txt') as f: flat_list=[word for line in f for word in line.split()] >>> flat_list ['line1', 'word1', 'word2', 'line2', 'word3', 'word4', 'line3', 'word5', 'word6']
使用print '\n'.join(flat_list)…可以创建与第一个示例相同的输出
print '\n'.join(flat_list)
或者,如果要在文件的每一行中嵌套单词列表(例如,从文件创建行和列的矩阵):
with open('words.txt') as f: matrix=[line.split() for line in f] >>> matrix [['line1', 'word1', 'word2'], ['line2', 'word3', 'word4'], ['line3', 'word5', 'word6']]
如果您想使用正则表达式解决方案,则可以在示例文件中过滤wordN和lineN键入单词:
wordN
lineN
import re with open("words.txt") as f: for line in f: for word in re.findall(r'\bword\d+', line): # wordN by wordN with no lineN
或者,如果您希望它成为带有正则表达式的逐行生成器:
with open("words.txt") as f: (word for line in f for word in re.findall(r'\w+', line))