python - 从字符串中提取多个子字符串

标签 python regex replace

我有一个复杂的字符串,想尝试从中提取多个子字符串。

字符串由一组项目组成,以逗号分隔。每个项目都有一个标识符 (id-n),用于内部用方括号括起来的一对单词。我只想得到括号内的单词,它的末尾附有一个数字(例如“This-1”)。这个数字实际上表示提取后单词应该如何排列的位置。

#Example of how the individual items would look like
id1(attr1, is-2) #The number 2 here indicates word 'is' should be in position 2
id2(attr2, This-1) #The number 1 here indicates word 'This' should be in position 1
id3(attr3, an-3) #The number 3 here indicates word 'an' should be in position 3
id4(attr4, example-4) #The number 4 here indicates word 'example' should be in position 4
id5(attr5, example-4) #This is a duplicate of the word 'example'

#Example of string - this is how the string with the items looks like
string = "id1(attr1, is-1), id2(attr2, This-2), id3(attr3, an-3), id4(attr4, example-4), id5(atttr5, example-4)"

#This is how the result should look after extraction
result = 'This is an example'

有没有更简单的方法来做到这一点?正则表达式对我不起作用。

最佳答案

一个简单/天真的方法:

>>> z = [x.split(',')[1].strip().strip(')') for x in s.split('),')]
>>> d = defaultdict(list)
>>> for i in z:
...    b = i.split('-')
...    d[b[1]].append(b[0])
...
>>> ' '.join(' '.join(d[t]) for t in sorted(d.keys(), key=int))
'is This an example example'

您的示例字符串中有重复的 example 位置,这就是代码中重复 example 的原因。

但是,您的 sample 也不符合您的要求 - 但此结果符合您的描述。根据位置指示符排列单词。

现在,如果你想去掉重复项:

>>> ' '.join(e for t in sorted(d.keys(), key=int) for e in set(d[t]))
'is This an example'

关于python - 从字符串中提取多个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17057453/

相关文章:

Python Tkinter : multiple images and text on a BIG button?

python - Django:ModelSerializer 的自定义字段映射

javascript - 似乎 JavaScript RegExp 没有找到 "leftmost longest"

php - 从 PHP 中的字符串替换此十六进制字符

java - 替换字符串中的子字符串

python - 如何使用 TensorFlow 在 ROI 周围创建边界框

python - Openpyxl 次要网格线

sql - Redshift 提取两个模式之间的字符串 (regexp_substr)

javascript - 拒绝绝对无效的电子邮件地址的最不坏的正则表达式是什么?

javascript - 使用正则表达式查找引号中的逗号并替换为 HTML 等效项