Python纯文本正则表达式解析

2024-04-29 15:42:53 发布

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

我需要编写一个小解析器来从表单中提取数据。在

数据将一直以一致的模式发布。具体如下:

Panakamanana
104412=Trident of Corrupted Waters
104411=Immerseus' Crystalline Eye
104435=Stonetoe's Tormented Treads
104455=Reality Ripper Ring
99716=Chest of the Cursed Protector
104509=Laser Burn Bracers
104531=Haromm's Talisman
99722=Gauntlets of the Cursed Protector
104562=Ring of Restless Energy
104606=Gleaming Eye of the Devilsaur
99725=Helm of the Cursed Protector
99719=Shoulders of the Cursed Protector
104616=Ticking Ebon Detonator
105686=Hellscream's Pig Sticker

我唯一感兴趣的数据是=号之前的每个整数。我希望能够对这些进行迭代,这样也许可以将它们放入dict或数组中,或者其他一些东西。在


Tags: ofthe数据解析器表单模式cursedeye
3条回答

您可以简单地执行以下操作:

new_list = [int(line[:line.find('=')]) for line in your_list]

print new_list

有一种方法可以做到:

with open('somefile.txt') as f:
   next(f) # Skips the first line, which doesn't have =
   numbers = [line.split('=')[0] for line in f if len(line.strip())]

print(numbers)

如果要使用正则表达式:

^{pr2}$

只要split使用'='作为分隔符的字符串。实现这一点的最典型的方法是使用列表理解:

>>> [int(line.split('=')[0]) for line in your_lines[1:]]
[104412, 104411, ..., 105686]

其中your_lines是问题中演示的list。在

相关问题 更多 >