我有一个与此类似的文件:
RANDOMTEXTSAMPLE*
$SAMPLERANDOMTEXT
RANDOMSAMPLE*TEXT
我正在尝试提取末尾带有 * 的“sample”的所有实例并将其放入列表中。
我尝试过这样的事情:
import re
with open('file1.txt') as myfile:
content = myfile.read()
text = re.search(r'[0-9A-Z]{7}\*', content)
with open("file2.txt", "w") as myfile2:
myfile2.write(text)
但是我只会得到它找到的第一个结果。
任何有关如何获取列表中以 * 结尾的所有示例实例而不将 * 添加到列表的建议将不胜感激。
谢谢
编辑:小修正
最佳答案
你可以试试这个:
import re
samples = []
with open('file1.txt') as myfile:
for line in myfile.readlines():
if re.search(r'[0-9A-Z]{6}\*', line):
samples.append(line)
# print('SAMPLES: ', samples)
with open("file2.txt", "w") as myfile2:
for s in samples:
myfile2.write(s)
关于Python。从文件中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44713843/