|
发表于 2024-3-22 08:44:53
|
显示全部楼层
您的代码在停用词处理的地方卡住了。其中,您定义了一个`stopword_list`,用于存储停用词,但是未对其进行赋值。另外,`stop_list`被赋值为空列表,同样需要赋予一个初始值。
接下来,你可以尝试修改代码如下:
- import os
- import pandas as pd
- import re
- import jieba
- import jieba.posseg as psg
- def chinese_word_cut(mytext, dic_file, stop_file):
- jieba.load_userdict(dic_file)
- jieba.initialize()
- try:
- stopword_list = open(stop_file, encoding='utf-8').readlines()
- except:
- print("error in stop_file")
- return None
-
- stop_list = []
- flag_list = []
- for line in stopword_list:
- line = re.sub(u'\n|\\r', '', line)
- stop_list.append(line)
-
- word_list = []
- seg_list = psg.cut(mytext)
- for seg_word in seg_list:
- word = re.sub(u'','',seg_word.word)
- word = seg_word.word
- find = 0
- for stop_word in stop_list:
- if stop_word == word or len(word)
- find = 1 # 如果找到停用词,将find设置为1
- break
-
- if not find: # find为0时,表示未找到停用词
- word_list.append(word)
-
- return word_list
- # 使用示例
- mytext = "这是一段需要进行中文分词的文本"
- dic_file = "your_dictionary.txt" # 替换为你的自定义词典文件名
- stop_file = "your_stopwords.txt" # 替换为你的停用词文件名
- result = chinese_word_cut(mytext, dic_file, stop_file)
- print(result)
复制代码
在上述代码中,我添加了函数参数`dic_file`和`stop_file`,您需要根据实际情况替换为自己的词典文件和停用词文件。另外,我对`stopword_list`进行了赋值操作,将读取的停用词文件内容按行保存到列表中。最后,我对词列表进行了判断,如果某个词不是停用词,则将其添加到`word_list`中。最终,`word_list`存储了分词结果,可供后续处理使用。
希望能对您有所帮助!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|