【问题标题】:Read a text file. Search for a text based on pattern and print all the matches in another text file读取文本文件。根据模式搜索文本并在另一个文本文件中打印所有匹配项
【发布时间】:2014-12-02 19:22:17
【问题描述】:

我希望您能协助我编写 Python 代码来读取文本文件。根据模式搜索文本并将匹配的文本打印到另一个文本文件。

= 示例文件内容 = 1111/app/abc.jsf111。 asdvvas/小程序。此文本是 /apple.jsf,其中有苹果。此外,此文本可能有 /app.jsf

== 模式 ==

/app*.jsf

== 匹配 ==

/app/abc.jsf

/apple.jsf

/app.jsf

这是我的代码:

import re

source = open("test.txt", "r")
dest = open("op.txt", "w")

pattern = re.compile('/app*jsf')

for line in source.readlines():
    matches = pattern.findall(line)

    for word in matches:
       dest.write(line+"\n")

dest.close()

我的输出文件 (op.txt) 为空白。

【问题讨论】:

  • 正则表达式应该是/app.*jsf
  • p* 是“0 个或多个 p 字符”。你想要/app.*jsf.* = 零个或多个任意字符。

标签: python regex text-files


【解决方案1】:
pattern = re.compile('/app[^\.]*jsf')
#or maybe just
pattern = re.compile('/app.*jsf') #if your filename can have multiple periods in it eg app.app.app.jsf

应该工作......

regex("app*")# will match ap, app, appppp, appppppppppp

但是它不会匹配除 p 之外的任何东西,因为在正则表达式中,星号 (*) 表示 0 或更多,它与操作系统中的通配符不同目录搜索

【讨论】:

    【解决方案2】:

    替换:

    pattern = re.compile('/app*jsf') 
    

    与:

    pattern = re.compile('/app.*jsf') # .* means any character any number of times
    

    re.compile('/app*jsf') 仅匹配 /apjsf/appjsf/apppjsf/appppjsf 等这是不需要的,可能不会出现在您的文本文件中。这就是空文件的原因。

    【讨论】:

    • 也许将 * 更改为 *? 以使其不贪婪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多