從 pdf 檔案中,我將所有文本提取為字串,并通過洗掉所有雙空格、換行符(兩個或更多)、空格(如果有兩個或更多)以及每個點 (.) 將其轉換為串列。現在在我的串列中,如果串列的值僅包含特殊字符,則應排除該值。
pdfFileObj = open('Python String.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(0)
text=pageObj.extractText()
z =re.split("\n |[.]|\s{2,}",text)
while("" in z) :
z.remove("")
print(z)
我的輸出是
['split()', 'method in Python split a string into a list of strings after breaking the', 'given string by the specified separator', 'Syntax', ':', 'str', 'split(separator, maxsplit)', 'Parameters', ':', 'separator', ':', 'This is a delimiter', ' The string splits at this specified separator', ' If is', 'no', 't provided then any white space is a separator', 'maxsplit', ':', 'It is a number, which tells us to split the string into maximum of provi', 'ded number of times', ' If it is not provided then the default is', '-', '1 that means there', 'is no limit', 'Returns', ':', 'Returns a list of s', 'trings after breaking the given string by the specifie', 'd separator']
以下是一些僅包含特殊字符的值,我想洗掉它們。謝謝
uj5u.com熱心網友回復:
在將文本轉換為串列之前洗掉這些特殊字符。while("" in z) : z.remove("")在讀取text變數后洗掉并添加以下行:
text = re.sub('(a|b|c)', '', text)
在這個例子中,我的特殊字符是 a、b 和 c。
uj5u.com熱心網友回復:
使用正則運算式來測驗字串是否包含任何字母或數字。
import re
z = [x for x in z if re.search(r'[a-z\d]', x, flags=re.I)]
在正則運算式中,a-z匹配字母,\d匹配數字,因此[a-z\d]匹配任何字母或數字(并且該re.I標志使其不區分大小寫)。因此串列推導式包括任何z包含字母或數字的元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394043.html
下一篇:提高用資料填充熊貓資料框的速度
