如何匹配仅包含数字的单词周围的引号?

时间:2018-08-31 12:10:20

标签: python regex regex-negation

如何匹配数字附近的引号: 这是我所拥有的:

"Austria","AU","ULO1","185","34","4dera"

这是我需要的:

"Austria","AU","ULO1",185,34,"4dera"

这是我最近做过的事情:\"(?=\d)|(?<=\d)\", 但是这样做的问题是它也匹配以数字开头的单词,因此我无法将+*.放在后视或前瞻中。我试图用这样的1400行更改.csv文件。我可以用Notepad ++代替它,因为它支持正则表达式或python脚本。

4 个答案:

答案 0 :(得分:5)

list1 = ["Austria","AU","ULO1","185","34","4dera"]

list2 = []

for item in list1:    
    try:
        list2.append(int(item))
    except ValueError:
        list2.append(item)

应该为字符串strings返回int,为list2中的数字返回/** A test class. Detailed description of the test class * Usage: * @code * test a; * @endcode */ template<> class test { //some class }; /**@example TestExample.cpp * Simple example of how to use the test class */

答案 1 :(得分:5)

import re
s = '"Austria","AU","ULO1","185","34","4dera"'
print(re.sub(r'"(\d+)"',r'\1',s))

匹配"中包含的每个数字,并用不带"的数字替换。

答案 2 :(得分:4)

在记事本++中

搜索:\"(\d+)\" 替换为:\1

答案 3 :(得分:3)

您可以使用str.isdigit()

例如:

import csv

with open(filename, "r") as infile:
    reader = csv.reader(infile)
    for row in reader:
        print([int(i) if i.isdigit() else i for i in row])

输出:

['Austria', 'AU', 'ULO1', 185, 34, '4dera']