我有一个csv文件'description',它的第一列描述不同的属性。我想告诉Python从每一行复制前两个单词。然后将前两个单词保存到新的csv中。我查看了下面的链接,但无法得到我期望的结果。
How to get the first word in the string

import pandas as pd
import csv

with open('C:/Users/description.csv','r') as k:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
    print(" ".join(row.split(0)[:2]))

错误:
print(" ".join(row.split(0)[:2]))
AttributeError: 'list' object has no attribute 'split'


with open('thematchingresults.csv', 'w') as f:
    df.to_csv(f)

最佳答案

这将解决您的问题:
对于Python 3.x

import csv

with open("input.csv", "r") as inp, open("output.csv", "w", newline='') as outp:
    reader = csv.reader(inp, delimiter=";")
    writer = csv.writer(outp, delimiter=";")
    for row in reader:
        first_col = row[0]
        first_two_words = " ".join(first_col.split(" ")[:2])
        # You can write more information if you need to.
        writer.writerow([first_two_words])

对于Python2.7.x
import csv

with open("input.csv", "r") as inp, open("output.csv", "wb") as outp:
    reader = csv.reader(inp, delimiter=";")
    writer = csv.writer(outp, delimiter=";")
    for row in reader:
        first_col = row[0]
        first_two_words = " ".join(first_col.split(" ")[:2])
        # You can write more information if you need to.
        writer.writerow([first_two_words])

09-27 05:59