【发布时间】:2019-05-10 13:17:41
【问题描述】:
我正在从伪 xml 格式文件创建一个 json 文件。但是我在 json 对象之间得到逗号,这是我不想要的。
这是我得到的示例:
[{"a": a , "b": b } , {"a": a , "b": b }]
但是我想要这个:
{"a": a , "b": b } {"a": a , "b": b }
它可能不是一个有效的 json,但我希望它是这样的,以便我可以通过这样做来随机播放它:
shuf -n 100000 original.json > sample.json
否则就是一大行json
这是我的代码:
def read_html_file(file_name):
f = open(file_name,"r", encoding="ISO-8859-1")
html = f.read()
parsed_html = BeautifulSoup(html, "html.parser")
return parsed_html
def process_reviews(parsed_html):
reviews = []
for r in parsed_html.findAll('review'):
review_text = r.find('review_text').text
asin = r.find('asin').text
rating = r.find('rating').text
product_type = r.find('product_type').text
reviewer_location = r.find('reviewer_location').text
reviews.append({
'review_text': review_text.strip(),
'asin': asin.strip(),
'rating': rating.strip(),
'product_type': product_type.strip(),
'reviewer_location': reviewer_location.strip()
})
return reviews
def write_json_file(file_name, reviews):
with open('{f}.json'.format(f=file_name), 'w') as outfile:
json.dump(reviews, outfile)
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-f', '--file_name',action="store", dest="file_name",
help="name of the input html file to parse", default="positive.html")
options, args = parser.parse_args()
file_name = options.file_name
html = read_html_file(file_name)
reviews_list = process_reviews(html)
write_json_file(file_name,reviews_list)
第一个 [ ] 是因为 reviews = [],我可以手动删除它,但我也不想在我的 json 对象之间使用逗号。
【问题讨论】:
-
如果没有逗号就不是json
-
你不能那样做。你想要这个纯粹是为了展示吗?如果您以这种格式保存文件,它基本上会损坏。
-
除了@vidstige所说的,如果你想让它成为有效的json,不要删除[和]
-
我已经编辑了这个问题来解释我为什么要这样
标签: python json beautifulsoup