【问题标题】:Extracting specific information from a string list using regular expressions使用正则表达式从字符串列表中提取特定信息
【发布时间】:2017-01-17 12:36:36
【问题描述】:

我有一个包含数千个不同结构的 URL 值的字符串列表,我正在尝试使用正则表达式从 URL 值中提取特定信息。下面为您提供了一个示例 URL,您可以从中了解该特定 URL 的结构(请注意,这种格式还有许多其他记录,只是数据中的数字会发生变化):

url_id | url_text
15     | /course/123908/discussion_topics/394785/entries/980389/read

使用 python 中的re 库,我可以找到哪些 URL 具有这种结构:

re.findall(r"/course/\d{6}/discussion_topics/\d{6}/entries/\d{6}/read", text) 

但是,我还需要提取“394785”和“980389”值并创建一个可能如下所示的新矩阵:

url_id | topic_394785 | entry_980389 | {other items will be added as new column}
15     | 1            | 1            | 0       | 0     | 1    | it goes like this

有人可以帮我提取这些特定信息吗?我知道'str'的'split'方法可能是一种选择。但是,我想知道是否有更好的解决方案。

谢谢!

【问题讨论】:

  • 如果您的字符串由固定数量的字段组成,以/ 分隔,那么split() 最佳解决方案。
  • 为什么不直接使用正则表达式捕获组?
  • 是的,您可以使用带有re.finditer 的捕获组的正则表达式,以便访问整个匹配项。

标签: python regex pandas


【解决方案1】:

你的意思是这样的吗?

import re

text = '/course/123908/discussion_topics/394785/entries/980389/read'
pattern = r"/course/\d{6}/discussion_topics/(?P<topic>\d{6})/entries/(?P<entry>\d{6})/read"

for match in re.finditer(pattern, text):
    topic, entry  = match.group('topic'), match.group('entry')
    print('Topic ID={}, entry ID={}'.format(topic, entry))

输出

Topic ID=394785, entry ID=980389

【讨论】:

  • 感谢您的回答!但是,我还有另一个问题。是否可以在不使用循环的情况下将其应用于list
  • 类似[text1, text2, text3,...]
  • @renakre 我不确定。遍历列表有什么问题?
猜你喜欢
  • 2014-09-08
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 2021-05-24
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多