簡體   English   中英

如何使用Python將句子寫入CSV文件

[英]How to write a sentence into a CSV file using Python

我有這樣的句子!

如何使用“!”將句子寫入.CSV文件中 在第一欄中,“這很棒”在另一欄中?

您可以使用pandas to_csv方法

碼:

import pandas as pd

col1 = []
col2 = []
f = '!=This is great'

l1 = f.split('=')
col1.append(l1[0])
col2.append(l1[1])

df = pd.DataFrame()
df['col1'] = col1
df['col2'] = col2
df.to_csv('test.csv')

分割文本,並將其寫入輸出文件:

text  = open('in.txt').read() #if from input file
text = '!=This is great' #if not from input file

with open('out.csv','w') as f:
    f.write(','.join(text.split('=')))

輸出:

!,This is great

如果您有多行,則必須遍歷輸入文件並拆分每一行

當然,您可以使用帶有open()標准io進行編寫,並為每行手動使用逗號定界符進行編寫,但是python具有csv標准庫可為您提供幫助。 您可以指定dialect

In [1]: import csv   

In [2]: sentence="!=This is great"   

In [3]: with open("test.csv", "w", newline='') as f: 
   ...:     my_csvwriter = csv.writer(f) 
   ...:     my_csvwriter.writerow(sentence.split("=")) 

對於多個數據,假設它在列表中,則可以在寫入時對其進行遍歷。

with open("test.csv", "w", newline='') as f: 
     my_csvwriter = csv.writer(f)
     for sentence in sentences:
         my_csvwriter.writerow(sentence.split("="))

該庫有助於處理句子中的逗號,而不是自己處理。 例如,您有:

sentence = "!=Hello, my name is.."
with open("test.csv", "w", newline='') as f: 
     my_csvwriter = csv.writer(f)
     my_csvwriter.writerow(sentence.split("="))

# This will be written: !,"Hello, my name is.."
# With that quote, you could still open it in excel without confusing it
# and it knows that `Hello, my name is..` is in the same column

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM