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

2024-09-29 00:22:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试着识别句子中那些只由数字组成的单词。一旦我发现一个只由数字组成的单词,我就会对它进行某种操作。我可以对单个数字串进行这种操作,但如果字符串在句子中随机放置,我完全不知道如何操作

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

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

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?

Tags: and字符串inif数字字符单词start
1条回答
网友
1楼 · 发布于 2024-09-29 00:22:26

您可以这样做,从语句中提取数值,并将这些值传递给函数

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

相关问题 更多 >