示例文字文件:
["abc","123","apple","red","<a href='link1'>zzz</a>"],
["abc","124","orange","blue","<a href='link1'>zzz</a>"],
["abc","125","almond","black","<a href='link1'>zzz</a>"],
["abc","126","mango","pink","<a href='link1'>zzz</a>"]
预期输出:
abc 123 apple red 'link1'>zzz
abc 124 orange blue 'link1'>zzz
abc 125 almond black 'link1'>zzz
abc 126 mango pink 'link1'>zzz
我只是希望文件没有大括号,逗号用空格分隔,并且只获取行中最后一个元素的链接。
我尝试在Python中使用Lists。
我不知道如何继续。猜猜,我在某个地方出错了。帮助将不胜感激。在此先感谢:)
import sys
import re
Lines = [Line.strip() for Line in open (sys.argv[1],'r').readlines()]
for EachLine in Lines:
Parts = EachLine.split(",")
for EachPart in Parts:
EachPart = re.sub(r'[', '', EachPart)
EachPart = re.sub(r']', '', EachPart)
答案 0 :(得分:2)
如果您打算使用正则表达式删除[
和]
,则需要转义方括号以将它们作为文字符号进行匹配。他们是特殊的&#34;表示字符类边界的正则表达式字符因此需要特殊处理。
以下是正则表达式替换示例:
EachPart = re.sub(r'[\[\]]', '', EachPart)
请参阅demo
但是,您可以使用不需要正则表达式的str.replace(old, new[, max])
删除它们:
EachPart = EachPart.replace('[', '').replace(']', '')
请参阅demo
答案 1 :(得分:2)
这可以使用以下脚本完成:
import csv
import re
with open('input.txt', 'r') as f_input, open('output.txt', 'w') as f_output:
csv_input = csv.reader(f_input, delimiter='"')
for cols in csv_input:
if cols:
cols = [x for x in cols[1:-1:2]]
link = re.search(r"('.*?)<", cols[-1])
if link:
cols[-1] = link.group(1)
f_output.write('{}\n'.format(' '.join(cols)))
这将为您提供output.txt
包含:
abc 123 apple red 'link1'>zzz
abc 124 orange blue 'link1'>zzz
abc 125 almond black 'link1'>zzz
abc 126 mango pink 'link1'>zzz
更新 - 此代码的简化版本在repl.it上运行,以显示正确的输出。输入来自字符串,并显示输出。只需点击Run
按钮。
更新 - 已更新以跳过空白行
答案 2 :(得分:1)
无需使用regex to remove []
<强>代码:强>
import ast
with open("check.txt") as inp:
for line in inp:
check=ast.literal_eval(line.strip().strip(","))
print " ".join(check)
<强>输出:强>
abc 123 apple red <a href='link1'</a>
abc 124 orange blue <a href='link2'</a>
abc 125 almond black <a href='link3'</a>
abc 126 mango pink <a href='link4'</a>
但是为了得到href的值,我使用了regex
<强>代码1:强>
import re
import ast
with open("check.txt") as inp:
for line in inp:
check=ast.literal_eval(line.strip().strip(","))
if re.search("'([^']*?)'",check[4]):
check[4]=re.search("'([^']*?)'",check[4]).group(1)
print " ".join(check)
<强>输出:强>
abc 123 apple red link1
abc 124 orange blue link2
abc 125 almond black link3
abc 126 mango pink link4
根据您的要求
a="<a href='link1'>zzz</a>"
print re.search("'([^<]*?)<",a).group(1)
<强>输出:强>
link1'>zzz
<强>代码2:强>
import re
import ast
with open("check.txt") as inp:
for line in inp:
check=ast.literal_eval(line.strip().strip(","))
if re.search("'([^<]*?)<",a):
check[4]=re.search("'([^<]*?)<",a).group(1)
print " ".join(check)
答案 3 :(得分:1)
由于您的数据是有效的python数据结构,因此您可以使用ast.literal_eval
:
>>> import ast
>>> ast.literal_eval('''["abc","123","apple","red","<a href='link1'</a>"]''')
['abc', '123', 'apple', 'red', "<a href='link1'</a>"]
你也可以通过取第9个字符之后的所有字符直到第5个字符到最后一个来剪切字符串中的链接:
>>> s = "<a href='link1'</a>"
>>> s[9:-5]
'link1'
把它放在一起:
with open(outfile, 'w') as output:
with open(filename) as lines:
for line in lines:
values = ast.literal_eval(line)
values[4] = values[4][9:-5]
output.write(' '.join(values))
答案 4 :(得分:1)
每行可按如下方式处理:
>>>line = ["abc","123","apple","red","<a href='link1'>zzz</a>"]
>>>' '.join([k if 'href=' not in k else k[9:-4] for k in line])
"abc 123 apple red link1'>zzz"
答案 5 :(得分:0)
在文件的内容周围添加括号,您有一个有效的JSON对象:
import json
with open(filename) as lines:
output = json.loads("[" + lines.read() + "]")
现在您可以处理这些行,例如删除链接周围的锚点:
import re
for line in output:
line[4] = re.search(r"'([^']*)'", line[4]).group(1)
print " ".join(line)
答案 6 :(得分:0)
这段代码怎么样?
from __future__ import print_function, unicode_literals
import ast
import io
import re
import traceback
input_str = """["abc","123","apple","red","<a href='link1'</a>"],
["abc","124","orange","blue","<a href='link2'</a>"],
["abc","125","almond","black","<a href='link3'</a>"],
["abc","126","mango","pink","<a href='link4'</a>"]"""
filelikeobj = io.StringIO(input_str)
for line in filelikeobj:
line = line.strip().rstrip(",")
if line:
try:
line_list = ast.literal_eval(line)
except SyntaxError:
traceback.print_exc()
continue
for li in line_list[:-1]:
print(li, end=" ")
s = re.search("href\s*=\s*['\"](.*)['\"]", line_list[-1], re.I)
if s:
print(s.group(1), end="")
print()