保存每行的前两个单词

时间:2016-12-19 16:23:47

标签: python csv

我有一个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)

2 个答案:

答案 0 :(得分:3)

只需拆分你的字符串,然后加入它,但只保留2个第一项:

s = "My girlfriend is a rich lady"
print(" ".join(s.split()[:2]))

结果:

My girlfriend

答案 1 :(得分:2)

这可以解决您的问题:

适用于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])

适用于Python 2.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])