簡體   English   中英

如何從字符串列表中刪除特殊字符?

[英]How to remove special characters from a list of strings?

我正在讀取文件並在文件內容上使用正則表達式來執行一些操作。 在讀取文件時,我沒有在其中找到任何特殊字符,但是在文件內容上使用正則表達式並將其保存到列表后,數字前有特殊字符,如 \\t 和 \\xa0。

示例文件內容:

Hydrochloric Acid to pHÂ 3.3-5.0        q.s.    q.s.    q.s.    pH-regulator    Ph Eur, NF

應用正則表達式后變為:

Hydrochloric Acid to pHÂ\xa03.3-5.0\tq.s.\tq.s.\tq.s.\tpH-regulator\tPh Eur, NF

如何在沒有單獨的字符串替換技術的情況下刪除所有這些?

代碼:

def extract(filename):
    file=open(filename)
    file=file.read()
    print(file)
    print("wefewwEF3RF3")
    result = []
    med = r"(?:{})".format("|".join(map(re.escape, medicines)))
    pattern = re.compile(r"^\s*" + med + r".*(?:\n[^\w\n]*\d*\.?\d+[^\w\n]*(?:\n.*){2})?", re.M|re.IGNORECASE)
    result = pattern.findall(file)
#    result.encode('ascii', 'ignore')
    newresult = []
    for line in result:
        newresult.append((line.strip()))
    return newresult

newresult列表包含原始文件中不存在的所有這些特殊字符。

如果您知道所有這些特殊字符,您可以使用 str 的maketranstranslate方法將它們替換為以下方式的空格:

txt = 'Hydrochloric Acid to pHÂ\xa03.3-5.0\tq.s.\tq.s.\tq.s.\tpH-regulator\tPh Eur, NF'
t = ''.maketrans('\xa0\t','  ')
newtxt = txt.translate(t)
print(newtxt)

輸出

Hydrochloric Acid to pHÂ 3.3-5.0 q.s. q.s. q.s. pH-regulator Ph Eur, NF

maketrans接受 2 或 3 個參數。 它創建轉換表,然后可以在translate方法中使用它並按如下方式工作:來自maketrans第一個參數的每個字符maketrans被替換為來自maketrans第二個參數的相應字符(因此它們必須具有相等的長度)並且每個字符出現在第三個參數中的 maketrans 被刪除。 在上面的例子中, \\xa0被替換為空格, \\t被替換為空格。

在此處輸入圖片說明

你好,

你能在不同的 Python 版本下檢查你的代碼嗎? 它似乎在 3.8.0 上沒有錯誤。

def extract(filename):
    file='Hydrochloric Acid to pHÂ 3.3-5.0        q.s.    q.s.    q.s.    pH-regulator    Ph Eur, NF'
    result = []
    med = r"(?:{})".format("|".join(map(re.escape, file)))
    pattern = re.compile(r"^\s*" + med + r".*(?:\n[^\w\n]*\d*\.?\d+[^\w\n]*(?:\n.*){2})?", re.M|re.IGNORECASE)
    result = pattern.findall(file)
    #result.encode('ascii', 'ignore')
    newresult = []
    for line in result:
        newresult.append((line.strip()))
    print(file)
    print (newresult)
    return newresult
extract('test')

暫無
暫無

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

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