gpt4 book ai didi

python - 在 Python 中使用空格字符作为分隔符将句子分成单词

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:42 25 4
gpt4 key购买 nike

我的数据结构类中有一个作业,我正在使用 Python 尝试解决它。我真的被 Python 困住了,生疏了,所以请耐心等待。

问题

Read a sentence from the console.
Break the sentence into words using the space character as a delimiter.
Iterate over each word, if the word is a numeric
value then print its value doubled, otherwise print out the word,
with each output on its own line.

Sample Run:
Sentence: Hello world, there are 3.5 items.

Output:
Hello
world,
there
are
7
items.

到目前为止我的代码...

import string
import re

def main():
string=input("Input a sentence: ")
wordList = re.sub("[^\w]", " ", string).split()
print("\n".join(wordList))
main()

这给了我这个输出:

>>> 
Input a sentence: I like to eat 7 potatoes at a time
I
like
to
eat
7
potatoes
at
a
time
>>>

所以我的问题是弄清楚如何提取数值然后将其加倍。我什至不知道从哪里开始。

我们将不胜感激任何反馈。谢谢!

最佳答案

只需尝试将值转换为 float 。如果失败,则假设它不是 float 。 :)

def main():
for word in input("Input a sentence: ").split():
try:
print(2 * float(word))
except ValueError:
print(word)

以上仍将打印 7.0 而不是 7,这并不严格符合规范。您可以使用简单的条件和 float 的 is_integer 方法来解决此问题。

关于python - 在 Python 中使用空格字符作为分隔符将句子分成单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18819012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com