1

IPython で実行するシェル スクリプトは、次のオブジェクトを返します。

results = ['{"url": "https://url.com", "date": "2020-10-02T21:25:20+00:00", "content": "mycontent\nmorecontent\nmorecontent", "renderedContent": "myrenderedcontent", "id": 123, "username": "somename", "user": {"username": "somename", "displayname": "some name", "id": 123, "description": "my description", "rawDescription": "my description", "descriptionUrls": [], "verified": false, "created": "2020-02-00T02:00:00+00:00", "followersCount": 1, "friendsCount": 1, "statusesCount": 1, "favouritesCount": 1, "listedCount": 1, "mediaCount": 1, "location": "", "protected": false, "linkUrl": null, "linkTcourl": null, "profileImageUrl": "https://myprofile.com/mypic.jpg", "profileBannerUrl": "https://myprofile.com/mypic.jpg"}, "outlinks": [], "outlinks2": "", "outlinks3": [], "outlinks4": "", "replyCount": 0, "retweetCount": 0, "likeCount": 0, "quoteCount": 0, "conversationId": 123, "lang": "en", "source": "<a href=\\"mysource.com" rel=\\"something\\">Sometext</a>", "media": [{"previewUrl": "smallpic.jpg", "fullUrl": "largepic.jpg", "type": "photo"}], "forwarded": null, "quoted": null, "mentionedUsers": [{"username": "name1", "displayname": "name 1", "id": 345, "description": null, "rawDescription": null, "descriptionUrls": null, "verified": null, "created": null, "followersCount": null, "friendsCount": null, "statusesCount": null, "favouritesCount": null, "listedCount": null, "mediaCount": null, "location": null, "protected": null, "linkUrl": null, "link2url": null, "profileImageUrl": null, "profileBannerUrl": null}]}', ...]

一方、...は前のエントリに似たエントリが多いことを示します。type() によると、これは slist です。前述のシェル スクリプトのドキュメントによると、これは jsonlines ファイルです。

最終的に、これを csv オブジェクトに変換したいと思います。ここで、キーは列であり、値は値であり、各エントリ (上記のようなもの) は行です。次のようなものです:

url              date                       content   ...
https://url.com  2020-10-02T21:25:20+00:00  mycontent ...

ここで提案されたソリューションを試しましたが、次のようなキーと値のペアを持つデータ フレームを受け取ります。

import pandas as pd
df = pd.DataFrame(data=results)
df = df[0].str.split(',',expand=True)
df = df.rename(columns=df.iloc[0]) 
4

1 に答える 1

1

サンプル データにはいくつかの問題が含まれていますが、それらを修正すると次のようになります。

import json
import pandas as pd

fragment = '{"url": "https://url.com", "date": "2020-10-02T21:25:20+00:00", "content": "mycontent\\\\nmorecontent\\\\nmorecontent", "renderedContent": "myrenderedcontent", "id": 123, "username": "somename", "user": {"username": "somename", "displayname": "some name", "id": 123, "description": "my description", "rawDescription": "my description", "descriptionUrls": [], "verified": false, "created": "2020-02-00T02:00:00+00:00", "followersCount": 1, "friendsCount": 1, "statusesCount": 1, "favouritesCount": 1, "listedCount": 1, "mediaCount": 1, "location": "", "protected": false, "linkUrl": null, "linkTcourl": null, "profileImageUrl": "https://myprofile.com/mypic.jpg", "profileBannerUrl": "https://myprofile.com/mypic.jpg"}, "outlinks": [], "outlinks2": "", "outlinks3": [], "outlinks4": "", "replyCount": 0, "retweetCount": 0, "likeCount": 0, "quoteCount": 0, "conversationId": 123, "lang": "en", "source": "<a href=\\"mysource.com\\" rel=\\"something\\">Sometext</a>", "media": [{"previewUrl": "smallpic.jpg", "fullUrl": "largepic.jpg", "type": "photo"}], "forwarded": null, "quoted": null, "mentionedUsers": [{"username": "name1", "displayname": "name 1", "id": 345, "description": null, "rawDescription": null, "descriptionUrls": null, "verified": null, "created": null, "followersCount": null, "friendsCount": null, "statusesCount": null, "favouritesCount": null, "listedCount": null, "mediaCount": null, "location": null, "protected": null, "linkUrl": null, "link2url": null, "profileImageUrl": null, "profileBannerUrl": null}]}'

data = json.loads(fragment)
df = pd.DataFrame([data])
df.to_csv('test_out.csv')

注: この例ではサンプル データが修正されており、次のように変更されています。

  • "「ソース」で適切にエスケープされました
  • \nとしてエスケープされましたが、同様\\\\nに可能性があり\\nますが、csv に改行が必要だとは思いません

results がこれらのリストである場合:

import json
import pandas as pd

results = get_results_somewhere()

df = pd.DataFrame([json.loads(r) for r in results])
df.to_csv('test_out.csv')

入力のエラーが上記に限定されている場合は、次のように修正できます。

def fix_input(s):
    return regex.sub('(?<=<[^>]*?)(")', r'\\"', regex.sub(r'(?<=<[^>]*?)(\\)', '', regex.sub('\n', '\\\\\\\\n', s)))

これにより、以前にエスケープされた\\"内部がエスケープ解除され、内部が<>すべて置き換えられ、改行も「修正」されます。正規表現がそのように機能する理由を理解できない場合、それはおそらく別の質問です。"<>\\"

全部:

import json
import regex
import pandas as pd


def fix_input(s):
    return regex.sub('(?<=<[^>]*?)(")', r'\\"', regex.sub(r'(?<=<[^>]*?)(\\)', '', regex.sub('\n', '\\\\\\\\n', s)))


results = get_results_somewhere()
fixed_results = fix_input(results)

df = pd.DataFrame([json.loads(r) for r in fixed_results])
df.to_csv('test_out.csv')

注: これは、可変長の後読みを使用するため、regex代わりにサードパーティを使用します。re

于 2020-10-02T22:32:25.843 に答える