我是Python和這個平臺的新手,如果我的帖子不夠清楚,請原諒--我在表格設計上有點糾結。
我基本上是想去掉字串中的最后一個逗號,然后插入 "和 "字
220X, 226X.
226X.
我已經單獨處理了字串的最后一部分(最后一個逗號之后),并在其中添加了 "和 "字。現在我需要洗掉原始字串的最后一部分,并將該字串與包括 "和 "字在內的修正后的最后一部分連接起來。為此,我試圖洗掉字串的最后一部分(最后一個逗號之后),但我在這方面沒有什么收獲。
有沒有一種方法可以洗掉最后一個逗號之后的字串的最后一部分,或者甚至是其他方法來處理這個問題。
import pandas as pd
data= pd.read_csv("MCA Data.csv"/span>)
data["Temp"] = data["Public_Transport_Route_Desc"].str. rsplit(',').str[-1]
data["Desc_Check"]=data["Temp"] 。 str.startswith('T', na=False)
for index, row in data.iterrows()。
if data.loc[index, "Desc_Check"] == True:
data.loc[index, "Temp"] == "": "".
else:
data.loc[index, "Temp"] = "and" data.loc[index, "Temp"] here
謝謝!
uj5u.com熱心網友回復:
簡單的字串分割和重新連接。
注意,這在處理多個句子時有問題。你可能需要根據句號來分割句子......
注意,這在處理多個句子時有問題。
def replace_last_comma(instr: str) -> str:
if ',' in instr:
# split and rejoin, taking all commas excluding the last
result = ",".join(instr.split(",")[:-1]
# 添加最后部分的 "和"。
result = f"{result} and{instr.split(',') [-1]}"
return result
else:
return instr
print(replace_last_comma("this, is, a, test"/span>)
print(replace_last_comma("this is a, test")
print(replace_last_comma("this is a test")
輸出:
this, is, a and test
This is a and test
這是一個測驗
uj5u.com熱心網友回復:
我將使用str.rpartition.
。>>> s = "Foo, bar, baz, bang"
>>> start, sep, end = s.rpartition(", ")
>>> if sep:
... sep = " and ".
...
>>> result = start sep end
>>> print(result)
Foo, bar, baz and bang
rpartition將把一個字串分成三個部分:字串中最后出現的分隔符之前的部分、分隔符本身和分隔符之后的字串。然后你可以把分隔符改成你想要的樣子,再把字串重新組合起來。如果分隔符沒有出現在字串中,前兩個字串將是空的,整個字串在end.
>>> s = "Foo bar baz bang"
>>> start, sep, end = s.rpartition(" , ")
>>> if sep:
... sep = " and ".
...
>>> result = start sep end
>>> print(result)
Foo bar baz bang
uj5u.com熱心網友回復:
鑒于你正在使用pandas資料框架加載資料,你可以嘗試以下代碼:
def replace_last_comma_with_and(input_str。str)。)
comma_splits = input_str.rsplit(","/span>, 1)
if len(comma_splits) > 1:
return f"{comma_splits[0] 。 rstrip()}和{comma_splits[-1] .lstrip()}"
return input_str
data["Target"] = data["Public_Transport_Route_Desc"].apply(lambda x: replace_last_comma_with_and(x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324482.html
標籤:
