从输出创建数据框并将文件另存为CSV

时间:2018-02-12 12:52:30

标签: python-3.x pandas csv dataframe

我正在尝试创建一个数据帧并保存为csv.My代码和输出如下: 代码:

for dtags in html.find_all('div', attrs={'class':'wrap'}):
        for index, ptags in enumerate(dtags.find_all('p', attrs={'class':'partial_entry'})):
            if index == 0: #match the first element
                x = ptags.text
                z = print('Review:', x)

我的输出如下: 输出:

Review: I went on a family trip and it was amazing, I hope to come back soon. The room was small but what can you expect from New York. It was close to many things and the staff was perfect.I will come back again soon.
Review: Stayed here with my boyfriend for four nights, nice hotel. Didn’t have breakfast included so can’t comment on that. All staff very pleasant, rooms cleaned every day new towels every day. No complaints from us two. Wouldn’t come to New York again though. 
Review: Stayed in this hotel for 4 nights over new year 2017. It is in a good location, a

现在我正在使用代码创建数据帧,但我无法这样做,我的代码创建数据框如下:

import pandas as pd
results = []
results.append(z)
df = pd.DataFrame(results)
print(df)

此代码无法正常工作。需要帮助为我的输出创建数据框并将其另存为CSV。

1 个答案:

答案 0 :(得分:0)

以下是您的代码的略微修改版本:

results = []
for dtags in html.find_all('div', attrs={'class':'wrap'}):
        for index, ptags in enumerate(dtags.find_all('p', attrs={'class':'partial_entry'})):
            if index == 0: #match the first element
                x = ptags.text
                results.append({"review": x})
df = pd.DataFrame(results)
df.to_csv('data.csv', mode='a', header = False)
print(df)