簡體   English   中英

Python在特定子字符串之前提取十進制數

[英]Python Extract a decimal number before a specific substring

我想在特定子字符串之前提取一個數字(“百分比”)

我試圖使用split功能

str1="The percentage of success for Team A is around 7.5 per cent. What about their season ?"
print(str1.split("per cent",1)[0])

預期結果: "7.5"

實際結果: "The percentage of success for Team A is around 7.5"

您可以使用str.index查找per cent發生的索引,將字符串切片到結果索引,然后rstripsplit保留結果列表中的最后一個元素:

str1[:str1.index('per cent')].rstrip().split()[-1]
# '7.5'

您可以使用正則表達式:

import re

str1="The percentage of success for Team A is around 7.5 per cent. What about their season ?"

m = re.search('([0-9.-]+) per cent', str1)
m[1]
=>7.5

我做的是以下內容:我創建了一個正則表達式,匹配數字,短划線和點的任意組合(粗略地匹配可能為負的數字),然后是精確的文本per cent

我將數字指定為一個組,因此您可以通過訪問找到的匹配的第1個索引來獲取它。

我將介紹4種情況:A)僅使用表示的正小數. ,B)使用表示的任何小數. ,C)使用表示的多個小數. ,D)使用表示的多個小數. 或者,

A)假設您的浮點數始終以十進制表示法表示

import re

results = re.findall("\d+\.\d+",str1)[0]
print(results)
#'7.5'

B) 如果你還有NEGATIVE小數使用這個(更健壯):

results = re.findall(r"[-+]?\d*\.\d+|\d+",str1)

C) 如果你有MULTIPLE小數,請使用:

str1="The percentage of success for Team A is around 7.5 per cent and 2.3"

results = re.findall(r"[-+]?\d*\.\d+|\d+",str1)

len(results)
#2 since it found the 2 decimals.

# Use list comprehension to store the detected decimals.
final_results = [i for i in results]
print(final_results)
#['7.5', '2.3']

D) 最后,如果使用表示小數. (點)或, (逗號)然后使用超級健壯:

str1="The percentage of success for Team A is around 7.5 per cent and 2,3"

results = re.findall(r"\d+[.,]*\d*[.,]*\d*",str1)
final_results = [i for i in results]
#['7.5', '2,3']
str1.split('per cent')[0].split(' ')[-2]

暫無
暫無

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

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