簡體   English   中英

從 json 文件中的字符串中刪除標簽(\r、\n、<、>)

[英]Remove tags (\r, \n, <, >) from string in json-file

我知道以前有人問過類似的問題,但到目前為止我無法解決我的問題,所以提前道歉。

我有一個包含文本的 json 文件('test.json')。 文本顯示如下:

"... >>\r\n>> This is a test.>\r\n> \r\n-- \r\nMit freundlichen Gr&uuml;ssen\r\n\r\nMike Klence ..."

總體 output 應該是明文:

"... This is a test. Mit freundlichen Grüssen Mike Klence ..."

使用 beautifulsoup 我必須刪除那些 html 標簽。 但那些 >、\r、\n-- 仍然保留在文本中。 所以我嘗試了以下代碼:

import codecs
from bs4 import BeautifulSoup

with codecs.open('test.json', encoding = 'utf-8') as f:
    soup = BeautifulSoup(f, 'lxml')
    invalid_tags = ['\r', '\n', '<', '>']
    for tag in invalid_tags: 
        for match in soup.find_all(tag):
            match.replace_with()

print(soup.get_text())

但它對文件中的文本沒有任何作用。 我嘗試了不同的變體,但似乎沒有任何改變。

我怎樣才能讓我的代碼正常工作? 或者,如果有另一種更簡單或更快的方法,我也會很高興閱讀這些方法。

順便說一句,我在 anaconda 上使用 python 3.6。

非常感謝您的幫助。

您可以使用python內置函數replace()

with open('test.json', 'r', encoding = 'utf-8') as f:
    content = f.read()
    invalid_tags = ['\\r', '\\n', '<', '>', '-', ';']
    for invalid_tag in invalid_tags:
        content = content.replace(invalid_tag, '')
    content = content.replace('&u', 'ü')

print(content)

輸出:

...  This is a test.  Mit freundlichen GrüumlssenMike Klence ...

您也可以使用regex試試這個襯墊。

import re

string = "... >>\r\n>> This is a test.>\r\n> \r\n-- \r\nMit freundlichen Gr&uuml;ssen\r\n\r\nMike Klence ..."
updatedString = ''.join(re.split(r'[\r\n\<\>]+',string))

print(updatedString)

暫無
暫無

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

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