繁体   English   中英

获取字符串中数字的索引并提取数字前后的单词(不同语言)

[英]Get the indices of numbers in a string and extract words before and after the number (in different languages)

我尝试使用正则表达式并找到数字但没有找到整个数字的索引,而是只为数字中的第一个字符获取索引

text = "४०० pounds of wheat at $ 3 per pound"
numero = re.finditer(r"(\d+)", text) ####
op = re.findall(r"(\d+)", text) ####

indices = [m.start() for m in numero]
OUTPUT

[0, 25]

***Expected OUTPUT***
[0, 6]

在找到确切的索引并存储在列表中之后,提取单词会更容易。 这是我相信的吗? 你怎么看?

另外,我期待不同位置的单词,所以它不能是 static 方法

你用标签标记了这个问题,它是一个问题,你为什么不使用Spacy

查看带有 Spacy 3.0.1 的 Python 演示:

import spacy
nlp = spacy.load("en_core_web_trf")
text = "४०० pounds of wheat at $ 3 per pound"
doc = nlp(text)
print([(token.text, token.i) for token in doc if token.is_alpha])
## => [('pounds', 1), ('of', 2), ('wheat', 3), ('at', 4), ('per', 7), ('pound', 8)]
## => print([(token.text, token.i) for token in doc if token.like_num])
[('४००', 0), ('3', 6)]

这里,

  • nlp object 初始化为英文“大” model
  • doc是使用您的text变量初始化的 Spacy 文档
  • [(token.text, token.i) for token in doc if token.is_alpha]您提供包含其值 ( token.text ) 及其在文档中的位置 ( token.i ) 的字母单词列表
  • [(token.text, token.i) for token in doc if token.like_num]获取数字列表及其在文档中的位置。

您可以对其进行标记并以这种方式构建您的逻辑。 尝试这个:


number_index = []
text = "४०० pounds of wheat at $ 3 per pound"
text_list = text.split(" ")

# Find which words are integers.
for index, word in enumerate(text_list):
    try:
        int(word)
        number_index.append(index)
    except:
        pass

# Now perform operations on those integers
for i in number_index:
    word = text_list[i]
    # do operations and put it back in the list

# Re-build string afterwards

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM