syhwzy5050 2023-11-11 15:23 采纳率: 0%
浏览 4

结巴词性标注的代码修改,在韩版代码基础上

求机器语言专家修改代码。作为一个文本挖掘练习生,本人是在韩国学的文本挖掘相关的内容。然后想要自己修改代码用来中文文献的文本挖掘。现在主要问题在于结巴分词的代码逻辑好像跟在韩国用的代码逻辑不太一样,在词性标注阶段怎么修改都显示没有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,
                              )

如果有机器语言专家能帮助解答,感激不尽!

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-11-11 19:09
    关注

    【相关推荐】



    • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/7709018
    • 除此之外, 这篇博客: 机器学习-过拟合、正则化、稀疏性、交叉验证概述中的 在机器学习中,我们将模型在训练集上的误差称之为训练误差,又称之为经验误差,在新的数据集(比如测试集)上的误差称之为泛化误差,泛化误差也可以说是模型在总体样本上的误差。对于一个好的模型应该是经验误差约等于泛化误差,也就是经验误差要收敛于泛化误差,根据霍夫丁不等式可知经验误差在一定条件下是可以收敛于泛化误差的。 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 11月11日

悬赏问题

  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 在虚拟机环境下完成以下,要求截图!
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见