【问题标题】:Python 2.7 fnmatch NOT editing textPython 2.7 fnmatch 不编辑文本
【发布时间】:2021-05-01 13:19:51
【问题描述】:

我有一个包含 600k+ 字符串标签记录的文件,我正在尝试使用更新光标进行编辑,同时使用字符串模块和 fnmatch 来查找要编辑的模式。使用 fnmatch 的部分成功打印了匹配的记录,但没有更改/解析出匹配的模式。

没有错误,记录也没有变化。我的语法缺少什么?

(另外 - 附带问题,最后一个打印第 4 行语句只打印文件的第一条记录。)

结果样本与原始文本没有变化 1000STR92SE 8000STR37NW 7000STR35SW 8000STR44 1000STR88SE 1000STR74SE

但结果需要 92SE 37西北 35SW 44 88SE 74SE

def newlabel():
#Global Conversions - works on editing the string
    with arcpy.da.UpdateCursor(mvum_fc, newfields) as uc:
        for row in uc:
            if row[1] == None or row[1].startswith('0'):
                row[4] = '{}'.format(row[4].lstrip(ascii_letters).replace('_', "-").lstrip('0').replace(' ', '-'))

            if row[1] == None or row[1].startswith('-'):
                row[4] = '{}'.format(row[4].lstrip('-').lstrip('0'))
#Regional Conversions - lstrip and replace tried - not changing text.
            elif row[1].startswith('0118'):
                pattern = ('?000STR*')
                match = fnmatch.fnmatch(row[4], pattern)
                if match == True:
                    row[4] = '{}'.format(row[4].lstrip('?000STR'))
                    print(row[4])
            uc.updateRow(row)
            print(row[4])

【问题讨论】:

标签: python string python-2.7 fnmatch


【解决方案1】:

删除要删除的字符串中的?。它是用于模式匹配的通配符。

row[4] = '{}'.format(row[4].lstrip('000STR'))

【讨论】:

  • 我需要使用通配符,因为数据可能是 1000STR 或 2000STR - 等等。
  • lstrip() 不适用于通配符。它去除了我们作为输入提供的确切字符串。您必须单独进行模式匹配才能为其提供正确的输入
  • 感谢您的回复。您有使用通配符的替代建议吗?我有超过 50 万条记录,因此在模式匹配中使用通配符非常重要。
  • 你可以试试正则表达式:row[4]= re.sub( '.000STR' , "" , row[4] )
【解决方案2】:

我通过避免使用 .lstrip 解决了这个问题:

row[4] = '{}'.format(row[4].lstrip('000STR'))

只需将其替换为:

row[4] = '{}'.format(row[4][7:])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 2023-04-04
    • 2017-05-12
    • 2014-12-07
    相关资源
    最近更新 更多