求机器语言专家修改代码。作为一个文本挖掘练习生,本人是在韩国学的文本挖掘相关的内容。然后想要自己修改代码用来中文文献的文本挖掘。现在主要问题在于结巴分词的代码逻辑好像跟在韩国用的代码逻辑不太一样,在词性标注阶段怎么修改都显示没有twitter分词的功能。
韩国代码内容比较详细,它考虑到了在文本分析时的几种可能情况,所以有点复杂,我自己按照中文逻辑修改了一部分,为了避免遗漏,我把自己改的部分和原始代码一块放上来。
以下是韩国原版的代码:
def word_count(news_series, additional_words=None, stop_words_specific=None, dict_replace=None, dict_space=None):
now = datetime.datetime.now()
print(now)
lines = news_series
# 텍스트 클리닝
list_news = list()
for line in lines:
# 粘贴带有分写的单词
for word in dict_space.keys():
line = str(line).replace(word, dict_space[word])
# 특수문자들 제거
list_news.append(_text_cleaning(str(line)))
#twitter = Okt()
tagger = Twitter()
# list형태의 사용자 지정 단어 추가(명사)
if len(additional_words) != 0:
tagger.add_dictionary(additional_words, 'Noun')
# 카운트 하지 않을 단어 목록
if len(stop_words_specific) != 0:
tagger.add_dictionary(stop_words_specific, 'Noun')
# 형태소로 분리
sentences_tag = list()
for sentence in tqdm(list_news):
morph = tagger.pos(sentence)
sentences_tag.append(morph)
# 필요한 품사 리스트 - Noun, Adj, Verb 등
list_word_class = ['Noun']
# 형태소 분석한 결과 집합
document = list()
# 각각의 게시글
for sentence1 in sentences_tag:
list_each_write = list()
# 각각의 형태소
for word, tag in sentence1:
if ((tag in list_word_class) & (word not in stop_words_specific) & (len(word) != 1)) \
| ((len(word) == 1) & (word in additional_words)):
# 특정 단어들 replace
if word in list(dict_replace.keys()):
word = dict_replace[word]
list_each_write.append(word)
document.append(list_each_write)
# flattening
flatten = lambda x: list(itertools.chain.from_iterable(x))
text = nltk.Text(flatten(document))
num_token = 30000
print('\n전체 토큰 갯수: {}'.format(len(text.tokens)))
print('유니크 토큰 갯수: {}'.format(len(set(text.tokens))))
counts = text.vocab().most_common(num_token)
return counts, document
# 한글, 공백, as 를 제외하고 모두 제거
data['keyword'] = data['keyword'].str.replace("[^a-zA-Zㄱ-ㅎㅏ-ㅣ가-힣0-9 ]","")
data['keyword'].replace('', np.nan, inplace=True)
# 중복 제거
data = data.drop_duplicates(subset=['keyword']).dropna(subset=['keyword'])
# 단어사전에 추가할 단어
additional_words = ['조선족', '중국인'] # [필수 변경] 개별 데이터에서 형태소분석으로 나누어지지 않게 추가해야 할 단어 추가 (필요없다면 비워둠)
# 단어사전에서 제외할 단어
stop_words_specific = ['교포', '한국'] # [필수 변경] 제외할 단어가 있는 경우 추가 (필요없다면 비워둠. 비워둘 때에는 괄호는 남겨야 함-위아래 공통사항)
# 단어사전에서 단어 교체
dict_replace = {} # [필수 변경] 예시는 수면제를 약물로 변경하고 싶을 때를 나타냄. 변경이 필요할 경우 추가 (필요없다면 비워둠)
# 단어사전에서 띄어쓰기 제거
dict_space = {'중국인 동포': '중국인동포'} # [필수 변경] 띄어쓰기를 통일하고 싶을 때 추가 (필요없다면 비워둠)
#형태소 분석
lines = data['keyword'] # 형태소 분석할 column 명
counts, document = word_count(lines,
additional_words,
stop_words_specific,
dict_replace=dict_replace,
dict_space=dict_space
)
以下是我修改的代码,其中有问题的部分就在第二行,psg的使用问题。这个模块的无法使用影响到了后面的各种代码的编写,所以还是蛮麻烦的。我希望其他部分不改,就把词性分析模块调出来,能正常完成token的计数。
def word_count(news_series, additional_words=None, stop_words_specific=None, dict_replace=None, dict_space=None):
#此处与词表相连接,停用词表等
lines = news_series
list_news = list() #引入一个新闻列表
sentences_tag = list()
#利用jieba进行词性标注,这里可能有问题,是tagger的问题
seg=psg.cut(sentences_tag)
# 添加 list 类型的自定义单词(名词)
if len(additional_words) != 0:
seg.add_dictionary(additional_words, 'Noun')
# 停用词列表
if len(stop_words_specific) != 0:
seg.add_dictionary(stop_words_specific, 'Noun')
# 词素分离
for sentence in tqdm(list_news):
morph = seg.pos(sentence)
sentences_tag.append(morph)
# 所需词性列表 - Noun、 Adj、 Verb 等
list_word_class = ['Noun']
# 词素分析结果集合
document = list()
# 句子切分
for sentence1 in sentences_tag:
list_each_write = list()
# 词素切分
for word, tag in sentence1:
if ((tag in list_word_class) & (word not in stop_words_specific) & (len(word) != 1)) \
| ((len(word) == 1) & (word in additional_words)):
# 特定单词替换
if word in list(dict_replace.keys()):
word = dict_replace[word]
list_each_write.append(word)
document.append(list_each_write)
# 压平,降维函数
flatten = lambda x: list(itertools.chain.from_iterable(x))
text = seg.Text(flatten(document))
num_token = 5000
print('\n整体分词个数: {}'.format(len(text.tokens)))
print('唯一分词个数: {}'.format(len(set(text.tokens))))
counts = text.vocab().most_common(num_token)
return counts, document
# 去重
data = data.drop_duplicates(subset=['keyword']).dropna(subset=['keyword'])
# 分离前添加的单词表
additional_words = ['', '']
# 分离前去除的单词表,停用词
stop_words_specific = ['', '']
# 分离前替换的单词(敏感单词或多义单词的替换)
dict_replace = {}
#词素分析 要 添加空白间隔 ,词性标注,通用表,添加表,交换词,指定所需词性,压平 不要 逗号等标点,数字,特殊文字,单独分词工作(在之前先分开)
lines = data['keyword'] # 词素分析 column 名
counts, document = word_count(lines,
additional_words,
stop_words_specific,
dict_replace=dict_replace,
)
如果有机器语言专家能帮助解答,感激不尽!