我正在尝试将一些内容写入文件。问题是大内容被分成多行,我不想这样做。这是代码:-
from stackapi import StackAPI
SITE = StackAPI('stackoverflow')
SITE.max_pages=1
SITE.page_size=1
questions = SITE.fetch('questions', min=20, tagged='python', sort='votes')
with open('python_qna.txt', 'w') as file:
for quest in questions['items']:
if 'title' not in quest or quest['is_answered'] == False:
continue
title = quest['title']
question_id = quest['question_id']
top_answer = SITE.fetch('questions/' + str(question_id) + '/answers', order = 'desc', sort='votes', filter='!-.7zMlMaANYq')
file.write('- - ' + title + '\n')
file.write(' - ' + top_answer['items'][0]['body'])
以上代码的示例输出为:-
- - What does the "yield" keyword do?
- <p>To understand what <code>yield</code> does, you must understand what <em>generators</em> are. And before generators come <em>iterables</em>.</p>
<h2>Iterables</h2>
:
:
After all the lines
End of the answer line!
应该怎么做才能使文件具有一行问题,然后具有一行答案结构?
文件的最终结构应类似于:-
- - Question 1
- Answer 1
- - Question 2
- Answer 2
- - Question 3
- Answer 3
.
.
.
- - Question n
- Answer n
答案 0 :(得分:0)
string.splitlines()方法对我有用:-
top_answer = " ".join(top_answer.splitlines())