如何在python中查找和操纵句子中的单词?

问题描述 投票:0回答:1

我正在尝试识别仅由数字组成的句子中的单词。一旦找到仅由数字组成的单词,我便会对其进行某种操作。我可以对单个数字字符串执行此操作,但是如果字符串随机地放置在一个句子中,我绝对不知道该怎么做。

为此,我确认这只是一个数字,并迭代了它的字符,以便跳过第一个数字,将其余的更改为某些字母值,并在末尾添加一个新字符。这些细节不一定很重要。我正在尝试找到一种以相同方式处理句子中数字的每个随机“单词”的方法。这可能吗?

我不应该使用任何高级功能。仅循环,枚举,链,字符串函数等。我觉得自己只是在想什么!

NUM_BRAILLE="*"
digits='1234567890'
decade="abcdefhij"


def numstuff(s):
    if len(s)==1 and s.isdigit():
        s=s+NUM_BRAILLE
    elif " " not in s and s.isdigit():
        start_s=s[:1]
        s=s[1:]
        for i in s:
            if i in digits:
                s=s.replace(i,decade[int(i)-1])
        s=start_s+s+NUM_BRAILLE
   else:
   #if sentence contains many " " (spaces) how to find "words" of numbers and treat them using method above?
python python-3.x string loops
1个回答
0
投票

您可以执行类似的操作以从句子中提取数值并将其传递给函数。

sentence = "This is 234 some text 888 with few words in 33343 numeric"

words = sentence.split(" ")
values= [int(word) if word.isdigit() else 0 for word in words]

print values

输出:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.