[英]How to sort values in DataFrame for both numerical and string values?
[英]Sort values for both str and int by ranking appearance in a string
我必須對字符串中的關鍵字和值進行排序。
這是我的嘗試:
import re
phrase='$1000 is the price of the car, it is 10 years old. And this sandwish cost me 10.34£'
list1 = (re.findall('\d*\.?\d+', phrase)) #this is to make a list that find all the ints in my phrase and sort them (1000, 10, 10.34)
list2= ['car', 'year', 'sandwish'] #this is to make a list of all the keywords in the phrase I need to find.
joinedlist = list1 + list2 #This is the combination of the 2 lists int and str that are in my sentence (the key elements)
filter1 = (sorted(joinedlist, key=phrase.find)) #This is to find all the key elements in my phrase and sort them by order of appearance.
print(filter1)
不幸的是,在某些情況下,因為“排序的”function 通過詞法排序工作,積分將以錯誤的順序打印。 這意味着在某些情況下,例如這種情況,output 將是:
['1000', '10', 'car', 'year', 'sandwich', '10.34']
代替:
['1000', 'car', '10', 'year', 'sandwich', '10.34']
因為汽車出現在初始短語中的 10 之前。
詞法排序與它無關,因為你的排序key
是原始短語中的position; 所有排序都是按數值(由find
返回的索引)完成的。 '10'
出現“亂序”的原因是phrase.find
返回它的第一次出現,它在字符串的1000
部分內!
與其將句子分成兩個列表,然后嘗試用sort
重新組合它們,為什么不只使用一個正則表達式來選擇您想要保留的不同種類的東西呢? 這樣你根本不需要重新排序它們:
>>> re.findall('\d*\.?\d+|car|year|sandwish', phrase)
['1000', 'car', '10', 'year', 'sandwish', '10.34']
問題是10
和1000
每個都具有與 Python 的默認字符串查找相同的值。 兩者都位於字符串的開頭,因為10
是1000
的 substring。
您可以通過使用\b
字邊界實現對phrase
的正則表達式查找以實現您嘗試的方法,以便10
僅匹配字符串中的10
:
def finder(s):
if m:=re.search(rf'\b{s}\b', phrase):
return m.span()[0]
elif m:=re.search(rf'\b{s}', phrase):
return m.span()[0]
return -1
測試它:
>>> sorted(joinedlist, key=finder)
['1000', 'car', '10', 'year', 'sandwish', '10.34']
但是,如果將phrase
轉換為關鍵字的查找列表,會更容易。 您需要將year
作為關鍵字與phrase
中的years
進行一些處理; 您可以只使用正則表達式r'\d+\.\d+|\w+'
作為正則表達式來查找單詞,然后str.startswith()
來測試它是否足夠接近:
pl=re.findall(r'\d+\.\d+|\w+', phrase)
def finder2(s):
try: # first try an exact match
return pl.index(s)
except ValueError:
pass # not found; now try .startswith()
try:
return next(i for i,w in enumerate(pl) if w.startswith(s))
except StopIteration:
return -1
>>> sorted(joinedlist, key=finder2)
['1000', 'car', '10', 'year', 'sandwish', '10.34']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.