【问题标题】:Split the sentence into its tokens as a character annotation Python将句子拆分为其标记作为字符注释 Python
【发布时间】:2020-04-09 15:44:52
【问题描述】:

经过长时间的搜索,我没有找到任何问题的答案,这就是我决定将问题放在这里的原因。我正在尝试使用 RE 和 NLTK 获得一些特定的结果。 给定一个句子,在每个字符上我必须使用BIS 格式,即将每个字符标记为B (beginning of the token)I (intermediate or end position of the token)S for space。 例如,给定句子:

笔在桌子上。

系统必须提供以下输出:

BIISBIISBISBISBIISBIIIIB

可以读作:

<3-char token> <space> <3-char token> <space> <2-char token> <space> <2-char token> <space> <3-char token> <space> <5-char token> <1-char token>)

我的结果有点接近,但不是:

BIISBIISBISBISBIISBIIIIB 

我明白了:

BIISBIISBISBISBIISBIIIISB

意思是我在table 和点. 之间有空格 输出应该是:

<3-char token> <space> <3-char token> <space> <2-char token> <space> <2-char token> <space> <3-char token> <space> <5-char token> <1-char token>

我的是:

<3-char token> <space> <3-char token> <space> <2-char token> <space> <2-char token> <space> <3-char token> <space> <5-char token> <space> <1-char token>

到目前为止我的代码:

from nltk.tokenize import word_tokenize
import re
p = "The pen is on the table."
# Split text into words using NLTK
text = word_tokenize(p)
print(text)
initial_char = [x.replace(x[0],'B') for x in text]
print(initial_char)
def listToString(s):  
    # initialize an empty string 
    str1 = " " 
    # return string   
    return (str1.join(s)) 
new = listToString(initial_char)
print(new)
def start_from_sec(my_text):
    return ' '.join([f'{word[0]}{(len(word) - 1) * "I"}' for word in my_text.split()])
res = start_from_sec(new)
p = re.sub(' ', 'S', res)
print(p)

【问题讨论】:

  • 请看我的方法。我没有提供所有可能的替代方案,您需要首先提出更精确的规范/示例。随意发表评论。
  • @Wiktor Stribiżew 有没有办法使用 nltk tokenizer 来实现它?
  • 我不这么认为。

标签: python python-3.x nltk tokenize python-re


【解决方案1】:

您可以使用单个正则表达式来标记字符串:

(\w)(\w*)|([^\w\s])|\s

regex demo

模式详情

  • (\w)(\w*) - 第 1 组:任何单词字符(字母、数字或 _),然后第 2 组:任何 0 个或多个单词字符
  • | - 或
  • ([^\w\s]) - 第 3 组:除单词和空格字符外的任何字符
  • | - 或
  • \s - 一个空格字符

如果第 1 组匹配,则返回值为 B + 与第 2 组中字符数相同的 Is 数。如果第 3 组匹配,则替换为 B。否则,匹配一个空格,替换为S

这可以进一步定制,例如

  • 仅将_ 视为标点符号:r'([^\W_])([^\W_]*)|([^\w\s]|_)|\s'
  • 将 1 个或多个空格替换为单个 S: r'([^\W_])([^\W_]*)|([^\w\s]|_)|\s+'

Python demo online

import re
p = "The pen is on the table."
def repl(x):
    if x.group(1):
        return "B{}".format("I"*len(x.group(2)))
    elif x.group(3):
        return "B"
    else:
        return "S"

print( re.sub(r'(\w)(\w*)|([^\w\s])|\s', repl, p) )
# => BIISBIISBISBISBIISBIIIIB

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 2020-11-13
    • 2013-08-21
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多