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

2024-04-24 03:48:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我读了一个有以下文字的文件

    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

Tags: and文件theinfromtestisline
2条回答

我想这就是你想要的?你知道吗

[编辑:更新代码以反映问题的更改]

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,用于帮助测试正则表达式。你知道吗

干杯

用于捕获文本

例如,您可以搜索字符串文字this is::,然后创建一个子模式(.*?)(the?使之不贪婪)。你知道吗

示例

import re 

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

res = re.findall("this is::(.*?)\((.*?)\)", s)
for r in res:
    print(r)

输出

('b', 'test file')
('another', 'test file')
('a', 'test file')

用于在文件中追加行

我不清楚你想要什么,但如果你只是想附加到一个文件。。。见this post

示例

with open("test.txt", "a") as myfile:
    myfile.write("Found something!")

相关问题 更多 >