我会在这里使用 re.findall :
inp = '''first_word 3 5 7 @ 4
second_word 4 5 67| 5 ['''
matches = re.findall(r'\w+', inp)
print(matches) # ['first_word', '3', '5', '7', '4', 'second_word', '4', '5', '67', '5']
如果您想单独处理每一行,则只需在 CR?LF 上拆分输入并使用相同的方法:
inp = '''first_word 3 5 7 @ 4
second_word 4 5 67| 5 ['''
lines = inp.split('\n')
for line in lines:
matches = re.findall(r'\w+', line)
print(matches)
这打印:
['first_word', '3', '5', '7', '4']
['second_word', '4', '5', '67', '5']