gpt4 book ai didi

Python html提取关键字后的数字

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:20 25 4
gpt4 key购买 nike

line1 = " The median income for a household in the city was $64,411, and the median income for a family was $78,940. The per capita income for the city was $22,466. About 4.3% of families and 5.9% of the population were below the poverty line, including 7.0% of those under age 18 and 12.3% of those age 65 or over."

line2 = " The median income for a household in the city was $31,893, and the median income for a family was $38,508. Males had a median income of $30,076 versus $20,275 for females. The per capita income for the city was $16,336. About 14.1% of families and 16.7% of the population were below the poverty line, including 21.8% of those under age 18 and 21.0% of those age 65 or over."

预期输出:

household median income: $64,411
family median income: $78,940
per capital income: $22,466



[householdIncome, familyIncome, perCapitalIncome] = re.findall("\d+,\d+",line1)

第 1 行运行良好。第 2 行:

ValueError: too many values to unpack (expected 3)

主要目标是定位关键词后如何识别第一个数字/值。

有些线路他们没有人均收入,我可以接受为“”

最佳答案

正如其他人所指出的,您需要一些额外的编程逻辑。考虑以下示例,该示例使用正则表达式查找相关值并在必要时计算中位数:

import re, locale
from locale import atoi
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )

lines = ["The median income for a household in the city was $64,411, and the median income for a family was $78,940. The per capita income for the city was $22,466. About 4.3% of families and 5.9% of the population were below the poverty line, including 7.0% of those under age 18 and 12.3% of those age 65 or over.",
"The median income for a household in the city was $31,893, and the median income for a family was $38,508. Males had a median income of $30,076 versus $20,275 for females. The per capita income for the city was $16,336. About 14.1% of families and 16.7% of the population were below the poverty line, including 21.8% of those under age 18 and 21.0% of those age 65 or over."]

# define the regex
rx = re.compile(r'''
(?P<type>household|family|per\ capita)
\D+
\$(?P<amount>\d[\d,]*\d)
(?:
\s+versus\s+
\$(?P<amount2>\d[\d,]*\d)
)?''', re.VERBOSE)

def afterwork(match):
if match.group('amount2'):
amount = (atoi(match.group('amount')) + atoi(match.group('amount2'))) / 2
else:
amount = atoi(match.group('amount'))
return amount

result = {}
for index, line in enumerate(lines):
result['line' + str(index)] = [(m.group('type'), afterwork(m)) for m in rx.finditer(line)]

print(result)
# {'line1': [('household', 31893), ('family', 38508), ('per capita', 16336)], 'line0': [('household', 64411), ('family', 78940), ('per capita', 22466)]}

关于Python html提取关键字后的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42879745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com