【发布时间】: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