如何从 Python 中的字符串中提取信息?

How to extract information from a string in Python?

我有一个 csv 文件,其中包含一个奖项列,其中包含各种不同的提名和获奖。我想从这个 dataset 中的 awards 列中提取数据并将其分成几列。奖项包含获奖、一般提名以及某些类别(例如奥斯卡、BAFTA 等)的获奖和提名的详细信息。奖项列的示例输入如下所示。

我想将这些数据分成几列来分析数据。我们可以使用 python 来实现吗?我正在使用 pandas 访问 dataframe。示例预期输出如下所示。

看来您的数据结构不是特别好。如果保证格式为以下形式:

x wins & y nominations.

然后是下面的代码:

testStrings = ['1 win & 1 nomination.','2 wins.','5 nominations.', '3 wins & 8 nominations.', '2 wins.','9 wins.']

text = [i.split('&') for i in testStrings]

data=[]
for row in text:
    for t in row:
        winIndex = t.find('win')
        nomIndex = t.find('nom')
        if winIndex>0:
            w=int(t[:winIndex-1] )
        else:
            w=0
        if nomIndex>0:
            n=int(t[:nomIndex-1] )
        else:
            n=0
    data.append([w,n])

将为您提供列表 data,其中每一行的每个元素都是 [numWins, numNoms]

您可以通过搜索这些关键字(例如代码查找子字符串 "won" 和 "nom")来扩展它以应对不同的格式(例如 "Won 1 Primetime Emmy")。希望这能提供一些帮助。