簡體   English   中英

使用空格字符作為Python中的分隔符將句子分解為單詞

[英]Break the sentence into words using the space character as a delimiter in Python

我在我的Data Structures類中有一個賦值,我正在使用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
>>> 

所以我的問題是弄清楚如何提取數值然后加倍。 我不知道哪里開始。

任何反饋總是受到贊賞。 謝謝!

只是嘗試將值轉換為浮點數。 如果它失敗了,假設它不是浮點數。 :)

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

上面仍然會打印7.0而不是7,這不是嚴格的規格。 你可以用一個簡單的條件和is_integer方法來解決這個問題。

在這兒:

print("\n".join(wordList))

您可以使用列表推導來確定該單詞是否為數字。 也許是這樣的:

print('\n'.join(str(int(i)*2) if i.isdigit() else i for i in wordList)

這通過使用str.isdigit查找看似整數的str.isdigit ,將其轉換為整數,因此我們可以將其乘以2,然后將其轉換回字符串。


對於浮點數,那么try/except結構在這里很有用:

try:
    print('\n'.join(str(int(i)*2) if i.isdigit() else i for i in wordList)
except ValueError:
    print('\n'.join(str(float(i)*2) if i.isdigit() else i for i in wordList)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM