使用python进行词干分析

2024-06-16 14:22:15 发布

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

我有2个文件;root_文字.txt词缀_文字.txt。我想做的是匹配词缀中的词根_文字.txt替换词缀中的词根_文字.txt将“I”字和词根前替换为“E”字,词根后替换为“B”。你知道吗

例如:

read
xxxx

根_文字.txt你知道吗

reading
aaaxxxxyyy

词缀_文字.txt你知道吗

我想要的输出是:

r e a d i n g<TAB>I I I I B I I
a a a x x x x y y y<TAB>I I E I I I I B I I

我试着匹配根_文字.txt带词缀_文字.txt使用Linux命令:

fgrep -f "root_words.txt" "affix_words.txt"

但是如何用“I”字代替词根呢


Tags: 文件命令txtreadlinuxroottabwords
1条回答
网友
1楼 · 发布于 2024-06-16 14:22:15

您可以使用以下简单方法:

with open "root_words.txt" as rfile, "affix_words.txt" as afile:
    try:
        rw_start = aword.index(rword)
        rw_end = rw_start + len(rword)
        result = " ".join( "E" if n==rw_start-1 else \
                           "B" if n==rw_end else \
                           "I" for (n, letter) in enumerate(aword) )
    except:
        result = "NOT FOUND!"
    print("root: '{}', affixed: '{}', stemmed: '{}'".format(rword, aword, result))

示例:

root_words.txt

read
vote
like

affix_words.txt

reading
upvote
unlikely

输出:

root: 'read', affixed: 'reading', stemmed: 'I I I I B I I'
root: 'vote', affixed: 'upvote', stemmed: 'I E I I I I'
root: 'like', affixed: 'unlikely', stemmed: 'I E I I I I B I'

See this code running on ideone.com

相关问题 更多 >