我正在搜索一个文本文件(如下所示的示例文件),并尝试从每个组中选择各种数据。例如,我想从每个组中选择“random text-x”数据、“findMe”文本和每个组中的数字(例如,从组A“100-012”和“499-217”),尽管每个组中的数字计数未知。你知道吗
EXAMPLEFILE.TXT:
1. [**] random text group A [**]
2. random number of lines of text
3. findMe
4. stufff...100-012 qwerty...499-217
5. [**] random text group B [**]
6. random lines of text
7. findMe
8. [**] random text group C [**]
9. random number of lines of text
10. findMe
11. stufff...223-300 qwerty...888-888 zzzz...333-444
12. [**] continues......
我的代码显示在最后,但它只输出:
random text-A
findMe
['100-012', '499-217', '223-300', '888-888', '333-444']
我真的很难弄清楚我错在哪里。非常感谢您的帮助,谢谢。你知道吗
import re
def patternMatching(group, line):
section = re.findall(group, line)
for i in section:
randText = re.search('\]\s(.*?)\[', i)
result1 = randText.group(1)
print result1
findMe = re.search('findMe', line)
result2 = findMe.group()
print result2
numbers = re.findall('(\d{3}\-\d{3})',line)
print numbers
randomTextgroup = re.compile(r'\*{2}\].*\[\*{2}\].*\[\*{2}\]', re.DOTALL|re.S)
with open ("C:/Location/test.txt", 'r') as txt:
data=txt.read().replace('\n','\r')
a = randomTextgroup.findall(data)
for i in a:
patternMatching(randomTextgroup, i)
我想要得到的结果是:
random text group A
findMe
100-012 499-217
random text group B
findMe
random text group C
fineMe
223-300 888-888 333-444
对于这组数字,我并不介意它是以['223-300','888-888','333-444']的形式出现,还是以元组的形式出现——只要它被分组,我就可以使用它。你知道吗
我终于有了!:)感谢@AdamSmith和@sln的帮助和建议。事实上,主要因素是regex(@randomTextgroup)很贪婪。然后patternMatching()中的额外for循环导致没有数据…一个for循环太多。不管怎样,谢谢你:)
结果如下:
注意:对于其他读取器,输入文件保持不变(如原文章所述)
相关问题 更多 >
编程相关推荐