【问题标题】:How to find and manipulate words in sentences in python?如何在python中查找和操作句子中的单词?
【发布时间】:2019-10-26 02:13:13
【问题描述】:

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

要对一个字符串执行此操作,我确认它只是数字并遍历其字符,因此我跳过了第一个数字,将其余部分更改为某些字母值并在末尾添加一个新字符。这些细节不一定是重要的。我试图找到一种方法以相同的方式处理句子中的每个随机数字“单词”。这可能吗?

我不应该使用任何高级功能。只有循环、枚举、if 链、字符串函数等。我觉得我只是想多了!

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】:

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

    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
    

    输出:

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2022-06-10
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      相关资源
      最近更新 更多