【问题标题】:Use NLTK RegexTokenizer to tokenize text and write it to a CSV使用 NLTK RegexTokenizer 标记文本并将其写入 CSV
【发布时间】:2014-12-07 11:51:04
【问题描述】:

提前感谢您的帮助。我非常迷茫。我正在尝试导入一个语料库,然后让它将 trigram 打印到一个 csv 文件中,其中包含整个 trigram 的第一列旁边的两列中的频率分布和相对频率。但我对 RegexTokenizer 的理解不够好,无法做到这一点。下面的代码获得了 90% 的路径,但 RegexTokenizer 只查找字母,因此它将带有“不要走开”等连词的短语拆分为三元组:“不要走”

我需要它停止这样做。如果没有 RegexTokenizer,三元组看起来像这样: (u'middle', u'class', u'americans') 我想你可以使用 RegexTokenizer 只查找 u' 和 ' 之间的短语,但我不知道如何要做到这一点。

import nltk
import re
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
from nltk import FreqDist
import math 
from decimal import *
from nltk.tokenize import RegexpTokenizer, WhitespaceTokenizer
import csv

#this imports the text files in the folder into corpus called speeches
corpus_root = '/Users/root...'
speeches = PlaintextCorpusReader(corpus_root, '.*\.txt')

print "Finished importing corpus"

tokenizer = RegexpTokenizer(r'\w+')
raw = speeches.raw().lower()
tokens = tokenizer.tokenize(raw)
tgs = nltk.trigrams(tokens)
fdist = nltk.FreqDist(tgs)
minscore = 200
numwords = len(raw)
c = csv.writer(open("TPNngrams.csv", "wb"))
for k,v in fdist.items():
    if v > minscore:
        rf = Decimal(v)/Decimal(numwords)
        firstword, secondword, thirdword = k
        trigram = firstword + " " + secondword + " " + thirdword
        results = trigram,v,rf
        c.writerow(results)
        print firstword, secondword, thirdword, v, rf

而且我也不断随机收到此错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 0: ordinal not in range(128)

【问题讨论】:

    标签: python csv unicode nltk tokenize


    【解决方案1】:

    要修复正则表达式标记器,请将您的标记器替换为:

    text = "We have 15 billion dollars in gold in our treasury; we don't own an ounce."
    tokenizer = RegexpTokenizer(r'(\w|\')+')
    tokens = tokenizer.tokenize(text)
    # ['We', 'have', '15', 'billion', 'dollars', 'in', 'gold', 'in', 'our', 'treasury', 'we', "don't", 'own', 'an', 'ounce']
    

    处理连词。

    我不确定错误在哪里引发(也许提供更多信息?)但我猜你正在导入 Python 不知道如何处理的奇怪字符。尝试添加

    # -*- coding: utf8 -*-
    

    在 .py 文件的最顶部。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      相关资源
      最近更新 更多