簡體   English   中英

如何打印字符串中的所有內容,直到 python 中的第一個數字?

[英]How would I print everything in a string up until the first number in python?

我有一個包含如下行的輸入文件:

“堪薩斯城酋長隊 42”

每行在單詞和數字之間包含隨機數量的空格。 我正在嘗試確定一種可以分割兩個值(單詞部分和數字部分)的方法。 我理想的 output 將是:

“堪薩斯城酋長”

“42”

有任何想法嗎?

簽出這個正則表達式:

import re

your_string = "Kansas City Chiefs 42"
items = re.split(r'\s+(?=\d)|(?<=\d)\s+', your_string)

print(items)

你得到了:

['Kansas City Chiefs', '42']

如果您的要求是在獲得第一個數字后立即閱讀拆分,那么下面應該可以工作。

st = "Kansas City Chiefs 42"
text_part = ""

for each in st:
    if each.isnumeric():
        break
    text_part += each
number_part = st.replace(text_part, "")
print(text_part)
print(number_part)

您可以在任何一個值上使用 you.strip() ,具體取決於您是否要在末尾保留空格

這是我的實現:

from nltk import word_tokenize

sentence = "Kansas City Chiefs 42"
tokens = word_tokenize(sentence)
word_phrases = " ".join([token for token in tokens if not token.isnumeric()])
numeric_phrase = " ".join([token for token in tokens if token.isnumeric()])
print(word_phrases)
print(numeric_phrase)

回答

# Python3 program to extract all the numbers from a string 
import re 
  
# Function to extract all the numbers from the given string 
def getNumbers(str): 
    array = re.findall(r'[0-9]+', str) 
    return array 
  
# Driver code 
str = "adbv345hj43hvb42"
array = getNumbers(str) 
print(*array) 

Output:

345 43 42

您可以在 python 中使用正則表達式。

import re
def getNumber(str):
  arr = re.findall(r'[0-9]+', str)
str1 = "Kansas City Chiefs 42"
numbers = getNumber(str1)
str_val = str1[str1.find(numbers[0]):] # Kansas City Chiefs 
print(" ".join(numbers))
# output -> 42

暫無
暫無

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

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