将字符串解析为具有两个键和一个值的字典

2024-04-29 15:58:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python程序prog1(mapper)在下面的三个字段中打印出来。它以

 print user, text, rt

第一个字段是用户名。其次是推文。第三是转发次数。试图找出TopN转发

下面是一个例子

inocybetech RT @ONAPproject: #ONAPAmsterdam is here! This first code release delivers a unified architecture for end-to-end, closed-loop…  5
jchawki RT @ONAPproject: #ONAPAmsterdam is here! This first code release delivers a unified architecture for end-to-end, closed-loop…  6
jchawki RT @opnfv: Congrats to @ONAPproject on Amsterdam, on its 1st platform release! Learn more about its unified architecture for e…  2
jchawki RT @jzemlin: Now Available! #ONAP Amsterdam brings globally shared implementation for network automation, based on OSS & open st…  3
jchawki RT @bdwick: Now Available! #ONAP Amsterdam brings globally shared implementation for network automation, based on OSS & open st…  1

我正在通过stdin将其管道传输到另一个Python程序prog2(reducer)。我的问题是如何把它读入一个有两个键(user和text)和值(retweet)的字典

如果我说

for line in sys.stdin

行没有捕获整个字符串。我需要做的是用两个键和一个值捕获字典中的三个字段。你知道吗

你能提个建议吗?我刚开始学Python

谢谢


Tags: totext程序forreleaseonendrt
1条回答
网友
1楼 · 发布于 2024-04-29 15:58:20

最好使用更易于解析的格式。如果打印的内容都是空格分隔的,那么在打印之后分隔各个字段可能会变得非常复杂,因为tweet的文本包含空格(甚至可能是换行符)。你知道吗

一种选择是生成/解析CSV(这有一个额外的优点,即您可以轻松地将输出与支持CSV输入的其他软件一起使用)。你知道吗

因此,writer(csvw.py)可以松散地表示为:

import csv
import sys

writer = csv.writer(sys.stdout, delimiter = ' ')

writer.writerow(['Name', 'Content\nof the message', 12])

读者(csvr.py):

import csv
import sys

reader = csv.reader(sys.stdin, delimiter = ' ')
stat = {}
for record in reader:
    name, message, cnt = record

    key = (name, message)
    stat[key] = int(cnt)

print(stat)

如果你这样做了:

python csvw.py | python csvr.py

你会得到:

{('Name', 'Content\nof the message'): 12}

相关问题 更多 >