Skip to main content
 首页 » 编程设计

python之读取文件行并在数字之前获取单词

2024年09月07日8txw1958

我正在编写代码,我在后台打开一个文本文件

f = open(FILENAME, 'r') 

我正在寻找写东西的特定行。

文档 1 中的示例:

Error you can find the Error in Section Nose 546516547 in Lower Part 211547

文档 2 中的示例:

Error the file break at you knee 3215467 in the element 51423165

所以我需要数字前的单词。 有任何想法吗? 一切都会帮助我。谢谢。

请您参考如下方法:

迭代每一行并使用下面的列表理解:

>>> line = 'Error you can find the Error in Section Nose 546516547 in Lower Part 211547' 
>>> line = line.split(' ') 
>>> [line[i-1] for i, e in enumerate(line) if e.isdigit()] 
['Nose', 'Part'] 

你也可以使用正则表达式:

>>> re.findall(r'([\w]+)\s[0-9]+', line) 
['Nose', 'Part']