我正在尝试将 JSON 文件转换为字典并应用键/值对,这样我就可以使用 groupbykey() 来基本上删除键/值对的重复数据。
这是文件的原始内容:
{"tax_pd":"200003","ein":"720378282"}
{“tax_pd”:“200012”,“ein”:“274027765”}
{“tax_pd”:“200012”,“ein”:“042746989”}
{“tax_pd”:“200012”,“ein”:“205993971”}
我已将其格式化为:
(u'201208', u'010620100')
(u'201208',u'860785769')
(u'201208',u'371650138')
(u'201208',u'237253410')
我想将它们转换为键/值对,这样我就可以在我的数据流管道中应用 GroupByKey。我相信我需要先把它变成一本字典?
我是 python 和谷歌云应用程序的新手,如果能提供一些帮助就太好了!
编辑:代码片段
with beam.Pipeline(options=pipeline_options) as p:
(p
| 'ReadInputText' >> beam.io.ReadFromText(known_args.input)
| 'YieldWords' >> beam.ParDo(ExtractWordsFn())
#| 'GroupByKey' >> beam.GroupByKey()
| 'WriteInputText' >> beam.io.WriteToText(known_args.output))
类 ExtractWordsFn(beam.DoFn):
def 过程(自身,元素):
Words = re.findall(r'[0-9]+', 元素)
产量元组(单词)
最佳答案
一个快速的纯 Python 解决方案是:
import json
with open('path/to/my/file.json','rb') as fh:
lines = [json.loads(l) for l in fh.readlines()]
# [{'tax_pd': '200003', 'ein': '720378282'}, {'tax_pd': '200012', 'ein': '274027765'}, {'tax_pd': '200012', 'ein': '042746989'}, {'tax_pd': '200012', 'ein': '205993971'}]
查看您的数据,您没有唯一的键来通过 tax_pd
和 ein
执行 key:value 操作。假设会发生冲突,您可以执行以下操作:
myresults = {}
for line in lines:
# I'm assuming we want to use tax_pd as the key, and ein as the value, but this can be extended to other keys
# This will return None if the tax_pd is not already found
if not myresults.get(line.get('tax_pd')):
myresults[line.get('tax_pd')] = [line.get('ein')]
else:
myresults[line.get('tax_pd')] = list(set([line.get('ein'), *myresults[line.get('tax_pd')]))
#results
#{'200003': ['720378282'], '200012': ['205993971', '042746989', '274027765']}
这样您就拥有了唯一的键,以及相应的唯一ein
值的列表。不完全确定这是否是您想要的。 set
会自动对列表进行重复数据删除,并且包装 list
会重新转换数据类型
然后您可以显式地通过 tax_id
进行查找:
myresults.get('200012')
# ['205993971', '042746989', '274027765']
编辑:要从云存储中读取,代码片段 here翻译成更容易使用:
with gcs.open(filename) as fh:
lines = fh.read().split('\n')
您可以使用他们的 api 文档设置您的 gcs 对象
关于python列表到字典的数据流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50841994/