[英]How I can extract the portion of words from the file using python3.6?
我想從文本文件中提取特定的單詞。
這是示例文本文件:
https://drive.google.com/file/d/0BzQ6rtO2VN95d3NrTjktMExfNkU/view?usp=sharing
請檢查一下。
我正在嘗試將字符串提取為:
"Name": "the name infront of it"
"Link": "Link infront of it"
從輸入文件說,我希望得到這樣的輸出:
"Name":"JTLnet"
"Link":"http://jtlnet.com"
"Name":"Apache 1.3"
"Link":"http://httpd.apache.org/docs/1.3"
"Name":"Apache"
"Link":"http://httpd.apache.org/"
.
.
.
"Name":"directNIC"
"Link":"http://directnic.com"
如果這些單詞在文件中的任何位置,則應將其提取到另一個文件中。
請讓我知道如何實現這種提取? 請將該文件視為大文件的一小部分。
另外,它是文本文件,而不是json。
請幫助我。
由於文本文件的格式不正確,因此唯一的選擇就是正則表達式。 以下代碼段適用於給定的示例文件。
請記住,這需要您將整個文件加載到內存中
import re, json
f = open(r'filepath')
textCorpus = f.read()
f.close()
# replace empty strings to non-empty, match regex easily
textCorpus = textCorpus.replace('""', '" "')
lstMatches = re.findall(r'"Name".+?"Link":".+?"', textCorpus)
with open(r'new_file.txt', 'ab+) as wf:
for eachMatch in lstMatches:
convJson = "{" + eachMatch + "}"
json_data = json.loads(convJson)
wf.write(json_data["Name"] + "\n")
wf.write(json_data["Link"] + "\n")
使用re.findall()
和str.split()
函數的簡短解決方案:
import re
with open('test.txt', 'r') as fh:
p = re.compile(r'(?:"Categories":[^,]+,)("Name":"[^"]+"),(?:[^,]+,)("Link":"[^"]+")')
result = [pair for l in re.findall(p, fh.read()) for pair in l]
print('\n'.join(result))
輸出(片段):
"Name":"JTLnet"
"Link":"http://jtlnet.com"
"Name":"Apache 1.3"
"Link":"http://httpd.apache.org/docs/1.3"
"Name":"Apache"
"Link":"http://httpd.apache.org/"
"Name":"PHP"
....
您的文件是格式錯誤的json,帶有多余的雙引號。 但這足以使json模塊無法加載它。 剩下的是較低級別的正則表達式解析。
假設:
"Name"
或"Link"
之后有趣的部分是:
:
) "
)括起來,不包含雙引號 您可以在每一行上使用簡單的re.finditer
處理文件:
rx = re.compile(r'(("Name":".*?")|("Link":".*?"))')
with open(inputfile) as fd:
for line in fd:
l = rx.finditer(line)
for elt in l:
print(elt.group(0))
如果要將數據輸出到另一個文件,只需在上述代碼片段之前使用open(outputfile, "w") as fdout:
將其打開,然后將打印行替換為:
fdout.write(elt.group(0) + "\n")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.