【问题标题】:Extracting only genres from the string仅从字符串中提取流派
【发布时间】:2019-07-08 08:39:33
【问题描述】:

我有一个格式如下的字符串

[{'id': 35, 'name': 'Comedy'}]
[{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name' : 'Drama']

等等。 我想提取喜剧、戏剧等的价值观

我尝试使用以下 RE 没有成功。

('([^'])*')

我希望得到'name'之后的字符串部分:对于同一列表中 {} 下的每个字符串。例如[{'id': 35, 'name': 'Comedy'}]

我的数据来自熊猫数据框:

【问题讨论】:

  • 这看起来几乎是 JSON,但不是相当 JSON。为什么你有这种格式的数据?它是什么格式?您不应该使用任何格式解析器来解析这种格式并将其视为本机数组和对象吗?
  • 我要解析的数据是 pandas 数据框列中的一个条目。我只想提取 Comedy 、 Drama 等单词并将其替换为现有的 Json-like-String .另外,当我尝试通过 for 循环访问对象时,Python 默认将对象转换为字符串。
  • 我们看到的真的是 string,还是 Python list-of-dicts 的输出……?!
  • 数据如下。我只想从列中的数据中提取信息。我不知道如何。这是数据图像的链接。 imgur.com/uL1K52m

标签: python pandas


【解决方案1】:

在这里,使用这个正则表达式。

import re
txt = """
[{'id': 35, 'name': 'Comedy'}]
[{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name' : 'Drama']
"""
results = re.findall("'name'\s*:\s*'([^']+)'", txt)
print(results)

打印:

['Comedy', 'Comedy', 'Drama']

如果您想要唯一的值,只需 set(results)

【讨论】:

  • 您分享的答案很有帮助,但我希望将所有条目分开。例如,对于 [{'id': 35, 'name': 'Comedy'}] 我想要 ['Comedy'] 而对于 [{'id': 35, 'name': 'Comedy'}, {' id': 18, 'name' : 'Drama'}] 我想要 ['Comedy','Drama'] 等等。
  • 感谢您的努力@palvarez 我会弄清楚其余的
  • @AdityaVartak 您可以尝试先使用正则表达式 \[.*?\] 提取每个列表
猜你喜欢
  • 2021-07-18
  • 2012-01-02
  • 2022-06-10
  • 2019-09-14
  • 1970-01-01
  • 2015-10-04
  • 2021-01-08
  • 1970-01-01
  • 2014-08-30
相关资源
最近更新 更多