Skip to main content
 首页 » 编程设计

python之如何读取、清理 START 和 END token 并将其附加到类似 csv 的文件

2024年09月07日7zhwl

我正在编写一个读取 csv 文件的教程:

# Read the data and append SENTENCE_START and SENTENCE_END tokens 
 
with open('data/reddit-comments-2015-08.csv', 'rb') as f: 
    reader = csv.reader(f, skipinitialspace=True) 
    reader.next() 
    # Split full comments into sentences 
    sentences = itertools.chain(*[nltk.sent_tokenize(x[0].decode('utf-  
        8').lower()) for x in reader]) 
    # Append SENTENCE_START and SENTENCE_END 
    sentences = ["%s %s %s" % (sentence_start_token, x,  
                               sentence_end_token) for x in sentences] 
    print "Parsed %d sentences." % (len(sentences)) 

但出现以下错误:

sentences = itertools.chain(*[nltk.sent_tokenize(x[0].decode('utf-8').lower()) for x in reader]) 

IndexError: list index out of range

谁能帮帮我。我是 nltk 的新手。

请您参考如下方法:

这不完全是一个 cvs 文件,但您可以将其作为一个文件。

使用 pandas:

import pandas as pd 
df = pd.read_csv('reddit-comments-2015-08.csv', sep='\0') 

[输出]:

body 
0   I joined a new league this year and they have ... 
1   In your scenario, a person could just not run ... 
2   They don't get paid for how much time you spen... 
3   I dunno, back before the August update in an A... 
4   No, but Toriyama sometimes would draw himself ... 

然后删除开头和结尾的空格:

df['body'][:100].astype(str).apply(str.strip) 

接下来,您会看到文本中有奇怪的 XML 转义符号(例如 >、< 等),因此在标记化之前,您必须取消转义它们:

import pandas as pd 
from nltk.tokenize.util import xml_unescape 
 
df = pd.read_csv('reddit-comments-2015-08.csv', sep='\0') 
df['body'].astype(str).apply(str.strip).apply(xml_unescape) 

现在您可以进行标记化了:

import pandas as pd 
from nltk.tokenize.util import xml_unescape 
 
df = pd.read_csv('reddit-comments-2015-08.csv', sep='\0') 
df['body'].astype(str).apply(str.strip).apply(xml_unescape).apply(word_tokenize) 

要添加 START 和 END token ,只需执行以下操作:

df['tokens'] = ['START'] + df['body'].astype(str).apply(str.strip).apply(xml_unescape).apply(word_tokenize) + ['END']