[英]How to remove all non-alphabetic characters from a string?
我一直在開發一個程序,它將采用一個十六進制文件,如果文件名以“CID”開頭,那么它應該刪除前 104 個字符,在那之后有幾個字。 我也想刪除單詞后的所有內容,但問題是我要隔離的部分長度不同。
我的代碼目前是這樣的:
y = 0
import os
files = os.listdir(".")
filenames = []
for names in files:
if names.endswith(".uexp"):
filenames.append(names)
y +=1
print(y)
print(filenames)
for x in range(1,y):
filenamestart = (filenames[x][0:3])
print(filenamestart)
if filenamestart == "CID":
openFile = open(filenames[x],'r')
fileContents = (openFile.read())
ItemName = (fileContents[104:])
print(ItemName)
輸入示例文件(從 HxD 中提取):
.........................ýÿÿÿ................E.................!...1AC9816A4D34966936605BB7EFBC0841.....Sun Tan Specialist.................9.................!...9658361F4EFF6B98FF153898E58C9D52.....Outfit.................D.................!...F37BE72345271144C16FECAFE6A46F2A.....Don't get burned............................................................................................................................Áƒ*ž
我已經開始刪除前 104 個字符,但我還想刪除“Sun Tan Specialist”之后的字符,它們的長度會有所不同,所以我只剩下那部分。
我感謝任何人能給我的任何幫助。
刪除字符串中非字母字符的一種方法是使用正則表達式 [ 1 ]。
>>> import re
>>> re.sub(r'[^a-z]', '', "lol123\t")
'lol'
編輯
第一個參數r'[^az]'
是捕獲將要刪除r'[^az]'
內容的模式(此處,通過將其替換為空字符串''
)。 方括號用於表示類別(該模式將匹配該類別中的任何內容), ^
是“非”運算符,而az
表示所有小型大寫字母字符。 更多信息在這里:
https://docs.python.org/3/library/re.html#regular-expression-syntax
因此,例如,要保留大寫字母和空格,它將是:
>>> re.sub(r'[^a-zA-Z ]', '', 'Lol !this *is* a3 -test\t12378')
'Lol this is a test'
但是,從您在問題中提供的數據來看,您需要的確切過程似乎比“擺脫非字母字符”要復雜一些。
您可以使用filter
:
import string
print(''.join(filter(lambda character: character in string.ascii_letters + string.digits, '(ABC), DEF!'))) # => ABCDEF
你在評論中提到你把繩子歸結為Sun Tan SpecialistFEFFBFFECDOutfitDFBECFECAFEAFADont get burned
從本質上講,此時您的目標是刪除所有未緊跟小寫字母的大寫字母,因為 Upper Lower 表示短語的開頭。 您可以使用 for 循環來執行此操作。
import re
h = "Sun Tan SpecialistFEFFBFFECDOutfitDFBECFECAFEAFADont get burned"
output = ""
for i in range(0, len(h)):
# Keep spaces
if h[i] is " ":
output += h[i]
# Start of a phrase found, so separate with space and store character
elif h[i].isupper() and h[i+1].islower():
output += " " + h[i]
# We want all lowercase characters
elif h[i].islower():
output += h[i]
# [1:] because we appended a space to the start of every word
print output[1:]
# If you dont care about Outfit since it is always there, remove it
print output[1:].replace("Outfit", "")
輸出:
Sun Tan 專家套裝 不要被燙傷
Sun Tan 專家 不要被燙傷
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.