如何在python中编辑.csv以继续NLP

时间:2015-10-19 19:37:27

标签: python csv nlp nltk

您好我对编程不是很熟悉,在研究我的任务时发现了Stackoverflow。我想在.csv文件上进行自然语言处理,该文件看起来像这样并且有大约15.000行

    ID | Title        | Body
    ----------------------------------------
    1  | Who is Jack? | Jack is a teacher... 
    2  | Who is Sam?  | Sam is a dog.... 
    3  | Who is Sarah?| Sarah is a doctor...
    4  | Who is Amy?  | Amy is a wrestler... 

我想阅读.csv文件并执行一些基本的NLP操作,并将结果写回新文件或同一文件中。经过一些研究python和nltk接缝成为我需要的技术。 (我希望是对的)。标记后我希望我的.csv文件看起来像这样

    ID | Title                 | Body
    -----------------------------------------------------------
    1  | "Who" "is" "Jack" "?" | "Jack" "is" "a" "teacher"... 
    2  | "Who" "is" "Sam" "?"  | "Sam" "is" "a" "dog".... 
    3  | "Who" "is" "Sarah" "?"| "Sarah" "is" "a" "doctor"...
    4  | "Who" "is" "Amy" "?"  | "Amy" "is" "a" "wrestler"... 

经过一天的研究并将各个部分放在一起后,我取得的成就就像这样

    ID | Title                 | Body
    ----------------------------------------------------------
    1  | "Who" "is" "Jack" "?" | "Jack" "is" "a" "teacher"... 
    2  | "Who" "is" "Sam" "?"  | "Jack" "is" "a" "teacher"...
    3  | "Who" "is" "Sarah" "?"| "Jack" "is" "a" "teacher"...
    4  | "Who" "is" "Amy" "?"  | "Jack" "is" "a" "teacher"... 

我的第一个想法是读取.csv中的特定单元格,执行操作并将其写回同一单元格。并且不知何故在所有行上自动执行此操作。显然,我设法读取一个单元格并将其标记化。但我无法在特定的细胞中写回来。而且我远离"自动对所有行进行操作"。如果可能的话,我将不胜感激。

我的代码:

    import csv
    from nltk.tokenize import word_tokenize 

    ############Read CSV File######################
    ########## ID , Title, Body#################### 

    line_number = 1 #line to read (need some kind of loop here)
    column_number = 2 # column to read (need some kind of loop here)
    with open('test10in.csv', 'rb') as f:
        reader = csv.reader(f)
        reader = list(reader)
        text = reader[line_number][column_number] 


        stringtext = ''.join(text) #tokenizing just work on strings 
        tokenizedtext = (word_tokenize(stringtext))
        print(tokenizedtext)

    #############Write back in same cell in new CSV File######

    with open('test11out.csv', 'wb') as g:
        writer = csv.writer(g)
        for row in reader:
            row[2] = tokenizedtext
            writer.writerow(row)

我希望我能正确地提出这个问题,有人可以帮助我。

2 个答案:

答案 0 :(得分:2)

pandas库将使这一切变得更加容易。

pd.read_csv()将更容易处理输入,您可以使用pd.DataFrame.apply()将相同的函数应用于列

以下是您希望如何工作的关键部分的快速示例。在.applymap()方法中,您可以使用word_tokenize()替换我的lambda函数,以将其应用于所有元素。

In [58]: import pandas as pd

In [59]: pd.read_csv("test.csv")
Out[59]:
                     0                          1
0  wrestler Amy dog is         teacher dog dog is
1      is wrestler ? ?  Sarah doctor teacher Jack
2        a ? Sam Sarah           is dog Sam Sarah
3       Amy a a doctor             Amy a Amy Jack

In [60]: df = pd.read_csv("test.csv")

In [61]: df.applymap(lambda x: x.split())
Out[61]:
                          0                               1
0  [wrestler, Amy, dog, is]         [teacher, dog, dog, is]
1      [is, wrestler, ?, ?]  [Sarah, doctor, teacher, Jack]
2        [a, ?, Sam, Sarah]           [is, dog, Sam, Sarah]
3       [Amy, a, a, doctor]             [Amy, a, Amy, Jack]

另见:http://pandas.pydata.org/pandas-docs/stable/basics.html#row-or-column-wise-function-application

答案 1 :(得分:1)

首先需要解析文件,然后分别处理(标记化等)每个字段。

如果我们的文件看起来像你的样本,我不会称之为CSV。您可以使用csv模块解析它,该模块专门用于读取各种CSV文件:将delimiter="|"添加到csv.reader()的参数中,以分隔您的行成细胞。 (并且不要以二进制模式打开文件。)但是您的文件很容易直接解析:

with open('test10in.csv', encoding="utf-8") as fp:  # Or whatever encoding is right
    content = fp.read()
    lines = content.splitlines()
    allrows = [ [ fld.strip() for fld in line.split("|") ] for line in lines ]

    # Headers and data:
    headers = allrows[0]
    rows = allrows[2:]

然后,您可以使用nltk.word_tokenize()rows的每个字段进行标记,然后从那里继续。