我正在使用 Python 從經常更改的表中提取資料 - 我使用的方法并不理想。我想要的是一種方法來拉出所有只包含一個字母的字串,而忽略任何 2 個或更多的字串。
我可能會得到的資料示例:
115 19A6 HYS8 568
在這個例子中,我想拉 115、19A6 和 568。
目前我正在使用 isdigit() 方法來確定它是否是一個數字,這會過濾掉所有帶有一個字母的數字,這適用于某些目的,但并不理想。
uj5u.com熱心網友回復:
嘗試這個:
string_list = ["115", "19A6", "HYS8", "568"]
output_list = []
for item in string_list: # goes through the string list
letter_counter = 0
for letter in item: # goes through the letters of one string
if not letter.isdigit(): # checks if the letter is a digt
letter_counter = 1
if letter_counter < 2: # if the string has more then 1 letter it wont be in output list
output_list.append(item)
print(output_list)
輸出:
['115', '19A6', '568']
uj5u.com熱心網友回復:
這是一個帶有正則運算式的單行代碼:
import re
data = ["115", "19A6", "HYS8", "568"]
out = [string for string in data if len(re.sub("\d", "", string))<2]
print(out)
輸出:
['115', '19A6', '568']
uj5u.com熱心網友回復:
這是正則運算式 (regex) 的一個很好的例子,它可以作為內置re庫使用。
下面的代碼遵循以下邏輯:
- 定義資料集。添加了兩個示例來顯示包含兩個字母字符的字串被拒絕。
- 編譯要匹配的字符模式。在這種情況下,零個或多個數字,后跟零個或一個大寫字母,以零個或多個數字結尾。
- 使用該
filter功能檢測資料串列中的匹配項并作為串列輸出。
例如:
import re
data = ['115', '19A6', 'HYS8', '568', 'H', 'HI']
rexp = re.compile('^\d*[A-Z]{0,1}\d*$')
result = list(filter(rexp.match, data))
print(result)
輸出:
['115', '19A6', '568', 'H']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531128.html
上一篇:有沒有辦法使用TestNG@DataProvider檢查控制臺中回傳的多個錯誤訊息
下一篇:用malloc復制字串的正確方法
