【问题标题】:delete empty quotes and pattern before it in python在python中删除它之前的空引号和模式
【发布时间】:2019-03-22 17:52:22
【问题描述】:

我有一个文件如下,只要有一个空值的键,我想删除键和空引号

我的文件

<items="20" product="abc" condition="new">
<items="10" product="" condition="new">
<items="50" product="xyz" condition="">
<items="" product="mno" condition="fair">

想要的输出

<items="20" product="abc" condition="new">
<items="10" condition="new">
<items="50" product="xyz">
<product="mno" condition="fair">

我尝试过这样的事情,这仅删除了引号。我想删除 "="

之前的引号和值
f= open('test.txt','r') 
A1=f.read()

for i in A1:
    if i=="''":
        A1.remove(i)
    print A1
    break

【问题讨论】:

  • 使用 XML 解析器。
  • 我假设您遇到了修改正在使用的迭代器的情况。 stackoverflow.com/questions/13593585/… 是一个类似的问题。您不能在 for each 循环中更改您正在迭代的列表
  • 另外,变量i 将包含完整的字符串。因此,如果该行完全为空白,您的代码只会删除该行。不可能,因为(如果我没记错的话)最后仍然是换行符。
  • 此外,在 python 之外,这可以通过一个简单的查找和替换 sed 脚本相当快(通常)完成。 s/ [A-z]*=""/ /g 是我首先想到的。可能过于宽泛,但应该仍然有效。

标签: python


【解决方案1】:

你可以使用正则表达式:

import re

with open('test.txt','r') as A1:
   for i in A1:
       print(re.sub('[a-z-]+=\"\" *', '', i))


【讨论】:

  • 这可以正常工作,但如果项目或产品名称带有“-”,则无法正常工作。我在这个 上测试了它,而不是输出 它输出了
  • 谢谢,但我没有看到您发布的代码有任何变化。
  • 我将正则表达式中的 [a-z] 更改为 [a-z-]。
【解决方案2】:

一个可能的解决方案是:

with open('test.txt','r+') as f:
     for line in f:
          Line=line[1:len(line)-1]
          L=Line.split()

          for k in L: 
               if("" not in k):
                     f.write(k)
               f.write(" ")


【讨论】:

    【解决方案3】:

    你可以编写一个函数来传递这些行:

    with open('in_file', 'r') as f:
        lines = f.readlines()
    
    def process_line(line):
        line = line.split('<')[1].rsplit('>')[0]
        valids = [val for val in line.split(' ') if '""' not in val]
        line = '<{}>\n'.format(' '.join(valids))
        return line
    
    with open('out_file', 'w') as f:
        for line in lines:
            f.write(process_line(line))
    

    【讨论】:

    • 我试过这个,得到索引错误 Traceback(最近一次调用最后一次):文件“test1.py”,第 11 行,在 f.write(process_line(line)) 文件“test1. py",第 4 行,在 process_line line = line.split('')[0] IndexError: list index out of range
    【解决方案4】:

    你可以使用正则表达式,

    with open('tmp.txt', 'r') as f_in:
            with open('tmp_clean.txt', 'w') as f_outfile:
                f_out = csv.writer(f_outfile)
                for line in f_in:
                    line = line.strip()
                    row = []
                    if bool(re.search('(.*="")', line)):
                        line = re.sub('[a-z]+=\"\"', '',line)
                        row.append(line)
                    else:
                        row.append(line)
                    f_out.writerow(row)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多