使用NLTK regexetkenizer标记文本并将其写入CSV

2024-10-01 05:02:31 发布

您现在位置:Python中文网/ 问答频道 /正文

提前谢谢你的帮助。我迷路了。我尝试导入一个语料库,然后让它将三元组打印到一个csv文件中,在包含整个三元组的第一列旁边的两列中有频率分布和相对频率。但我对RegexExtkenizer的理解还不够深入。下面的代码实现了90%的效果,但regexeckenizer只查找字母,因此它将带有连词的短语(如“don't go”)拆分成三元组:“don't go”

我需要它来停止那样做。如果没有regexecxkenizer,那么trigrams看起来是这样的:(u'middle',u'class',u'americans')我可以想象你可以使用regexeckenizer只找到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

我也经常随机地得到这个错误:

^{pr2}$

Tags: csvfromimportrawrootcorpus频率三元组
1条回答
网友
1楼 · 发布于 2024-10-01 05:02:31

要修复regex标记器,请将标记器替换为以下内容:

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不知道如何处理的奇怪字符。尝试添加

^{pr2}$

在你的.py文件的最上面。在

相关问题 更多 >