Skip to main content
 首页 » 编程设计

python之在文件中存在特定字符串后捕获单词,如果存在则添加一行

2025年01月19日30lyj

我读了一个包含以下文本的文件

    this is::b(test file). 
    extra this is::another(test file). 
    this is::a(test file) 

我能够读取文件并将其写入另一个文件。我想捕获之后的单词

this is:: and before '(' i.e 'b' from the first line and 'a' from the 3rd line and store it in a list and nothing from the 2nd line since it has extra word before 'this is' I tried using the Regular expression:

   for item in lines: 
     print(item) 
     fw.write(item) 
    found=None 
 
found=(re.search('this is::(.+?)[)]',y).group(1) 

其中y=从文件中读取的字符串

y=''.join(lines)      

但它只捕获 'b' 并在每行之后添加新行。

有人可以建议我应该如何实现它。 预期文件:

 this is::b(test file). 
 An extra line:b 
 extra this is:another(test file). 
 this is::a(test file). 
 An extra line:a 

请您参考如下方法:

我认为这符合您的要求?

[编辑:更新代码以反射(reflect)对问题的更改]

import re 
 
lines = ("this is::b(test file).", 
         "extra this is::another(test file)", 
         "this is::a(test file)", 
         "this is::another test") 
 
words = [] 
for line in lines: 
    words.append(line) 
    found = re.search('^this is::.*[(]', line) 
    if found is None: continue 
    word = line.split('::')[1].split('(')[0] 
    words.append(f"An extra line:{word}") 
 
for word in words:   
    print(word)  # You can save to file here instead of print 

产量

this is::b(test file). 
An extra line:b 
extra this is::another(test file) 
this is::a(test file) 
An extra line:a 

请注意,我为最简单的情况提供了一个正则表达式;如果您需要更好的正则表达式——您应该自己独立解决。这是一个很棒的工具,debuggex , 用于帮助测试正则表达式。

干杯