I have some data in a JSON file, and I have used the code below to write them into csv file, but I found that the each word in a sentence has occupied one column, I want to store whole sentence in a single column.
This is the code:
for line in open('test1.json', 'r'):
if not line.strip():
continue
data = json.loads(line)
text = data["text"]
filtered_text = clean_tweets(text)
print(filtered_text)
with open ('test1.csv', 'a', encoding='utf-8') as f:
csvWriter = csv.writer(f)
csvWriter.writerow(filtered_text)
f.close()
csv.writerow()
expects an iterable parameter. Each item in the iterable is placed in a column. Strings are iterable, hence you get a single character in each column.
Put the string(s) in a list:
csvWriter.writerow([filtered_text])
But since you seem to only have one column, using the csv
module is unnecessary. Just use:
with open('test1.csv', 'a', encoding='utf8') as f:
f.write(filtered_text + '\n') # add newline if needed
Another option:
with open('test1.csv', 'a', encoding='utf8') as f:
print(filtered_text,file=f) # will add the newline
csvWriter.writerow()
获取列表或类似的列-您需要提供例如csvWriter.writerow([tweet_id, filtered_tweet])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.