Spacy Python如何使用/计数



我使用space进行文本分析。我需要计算文本中包含表达式'1/2'的数字出现的次数。

如何计算数字"1"one_answers"2";单独不诉诸于正则表达式的操作?

我的代码:

for token in doc:
if token.pos_ =='NUM':
m.append(token.text)

for item in set(m):
print(f'"{item}" was found {m.count(item)} times in text')

就您的问题而言,您想要计算在表达式'1/2'弹出的文本中数字出现的次数。在这种情况下,下面的命令可以工作:

test_str = "I like 1/2 to code 1/2 a lot"
search_str = "1/2"
print(f"Number of occurrences: {test_str.count(search_str)}")
calc = eval("1/2") # evaluates the expression as pythonic code
print(f"The expression '1/2', calculated to float: {calc}")
# >>> Number of occurrences: 2
# >>> The expression '1/2', calculated to float: 0.5

我还添加了一种"计算"表达式的方法。您可以使用eval函数,它将把字符串作为python代码求值。希望这对你有帮助!

编辑:要计算表达式的总数,您可以这样做:
test_str = "I 1 would 1 like 1/2 to code 1/2 a lot"
search_str = "1/2"
digit_list = search_str.split('/') # creates list ['1', '2']
print(f"Number of occurrences of {search_str}: {test_str.count(search_str)}")
for digit in digit_list:
print(f"Number of occurrences of digit {digit}: {test_str.count(digit)}")
# >>> Number of occurrences of 1/2: 2
# >>> Number of occurrences of digit 1: 4
# >>> Number of occurrences of digit 2: 2

最新更新