如何使用python3.6从文件中提取部分单词?
我想从文本文件中提取特定单词。如何使用python3.6从文件中提取部分单词?,python,python-3.x,text-processing,Python,Python 3.x,Text Processing,我想从文本文件中提取特定单词。 下面是示例文本文件: 请审阅。 我试图将字符串提取为: "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" "Li
下面是示例文本文件:
请审阅。
我试图将字符串提取为:
"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。
请帮助我。由于文本文件格式不正确,您唯一的选择是regex。下面的代码段适用于给定的示例文件 请记住,这需要将整个文件加载到内存中
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))
输出(片段):
您的文件是格式错误的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))
如果要将数据输出到另一个文件,只需在上述代码段之前以fdout:的形式打开(outputfile,“w”),并将打印行替换为:
fdout.write(elt.group(0) + "\n")
它看起来很像json,您是否尝试过
json.load
?是的,我尝试过。对我不起作用。所以考虑将文件制作为文本。它可行吗?@RomanPerekhrest您能帮我一下吗?显示预期结果,至少是实际文件的一个片段(比如前5行)@RomanPerekhrest看到我已经编辑了我的问题,现在你可以看到了。你现在能帮我吗?我如何才能将输出写入另一个文件…这真是太棒了。
fdout.write(elt.group(0) + "\n")