在Python3.x中进行分词

1 投票
3 回答
2248 浏览
提问于 2025-04-16 11:33

我在python2.x中有以下代码:

class _CHAIN(object):

    def __init__(self, execution_context=None):
        self.execution_context = execution_context

    def eat(self, toktype, tokval, rowcol, line, logical_line):        
        #some code and error checking


operations = _CHAIN(execution_context)

tokenize(StringIO(somevalue).readline, operations.eat)

现在的问题是,在python3.x中,第二个参数不存在。我需要在进行分词(tokenize)之前先调用函数operations.eat()。那么在python3.x中,我该如何完成这个任务呢?一个想法是直接在'tokenize'语句之前(代码的最后一行)调用函数tokenize.eat()。但是我不太确定需要传递什么参数。我相信一定有更好的方法来做到这一点。

3 个回答

0

在编程中,有时候我们会遇到一些问题,尤其是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,特别是当我们不太了解这些工具的工作原理时。比如,有人可能在使用某个库时,发现它的某个功能没有按照预期工作,这时候就需要去查找原因。

通常,我们可以通过查看文档、搜索网上的解决方案,或者在像StackOverflow这样的社区提问来找到答案。社区里的其他程序员可能遇到过类似的问题,他们的经验和建议可以帮助我们解决困扰。

总之,遇到问题时不要慌张,利用好网络资源和社区的力量,通常都能找到解决办法。

from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import string
import pymorphy2
import re
import nltk
nltk.download('punkt')

reg =  re.compile('[^а-яА-Я ]')
morph = pymorphy2.MorphAnalyzer()
stop_words = stopwords.words('russian')

def sentence(words):
    words = reg.sub('', words)
    words = word_tokenize(words, language = 'russian')
    tokens = [i for i in words if (i not in string.punctuation)]  
    tokens = [i for i in tokens if (i not in stop_words)]
    tokens = [morph.parse(word)[0].normal_form for word in tokens]
    tokens = [i for i in tokens if (i not in stop_words)]
    
    return tokens

df['text']=df['text'].apply(str)    
df['text'] = df['text'].apply(lambda x: sentence(x))
df['text'] = df['text'].apply(lambda x: " ".join(x))
3

你正在使用一个有点古老的系统,在这个系统中,你需要给一个函数传递一个可迭代的对象和一个可以处理这些数据的可调用对象。新的方法在概念上更简单,而且在Python 2和3中都可以使用:

from tokenize import generate_tokens
for token in generate_tokens(StringIO(somevalue).readline):
    eat(token)

虽然在Python 3中这个用法技术上没有官方文档,但不太可能会被取消。Python 3中的官方tokenize函数期望接收的是字节,而不是字符串。目前有一个关于为字符串提供官方API的请求,但看起来这个请求进展不大。

2

根据这个链接 http://docs.python.org/py3k/library/tokenize.html,现在你应该使用 tokenize.tokenize(readline) 这个方法:

import tokenize
import io

class _CHAIN(object):

    def __init__(self, execution_context=None):
        self.execution_context = execution_context

    def eat(self, toktype, tokval, rowcol, line, logical_line):        
        #some code and error checking
        print(toktype, tokval, rowcol, line, logical_line)


operations = _CHAIN(None)

readline = io.StringIO('aaaa').readline

#Python 2 way:
#tokenize.tokenize(readline, operations.eat)

#Python 3 way:
for token in tokenize.generate_tokens(readline):
    operations.eat(token[0], token[1], token[2], token[3], token[4])

撰写回答