【问题标题】:Replacing strings and RegEx in a file替换文件中的字符串和正则表达式
【发布时间】:2020-01-16 11:32:08
【问题描述】:

这是我的第一个问题,我对 Python 还很陌生。

不过,在问之前我真的尝试了一些不同的东西:-D

我有一个文件 (test.txt),其中包含如下组织的一些文本:

name="NAME-ABC"                                                         NewName="GOOD MORNING"
name="NAME-123456"                                                      NewName="HELLO"
name="NAME-3"                                                           NewName="ALLO"

我试图获取的输出是一个包含先前值的字典,例如:

{"NAME-ABC":"GOOD MORNING","NAME-123456":"HELLO","NAME-3":"ALLO"}

使用一个小字典(在下面的示例中为“d”),我设法删除了 first name= 部分并将结束行替换为逗号,但中间部分(包含不一致数量的空格和制表符 + NewName =),我无法处理它。

到目前为止我的代码是:

d =    {
  "name=": "",
  "\n": ","}


for x in range(len(d)):

    with open("test.txt") as f:
        newText=f.read().replace(list(d.items())[x][0], list(d.items())[x][1])

    with open("test.txt", "w") as f:
        f.write(newText)

这给了我一个 text.txt 文件如下:

"NAME-ABC"                                                      NewName="GOOD MORNING",
"NAME-123456"                                               NewName="HELLO",
"NAME-3"                                                        NewName="ALLO"

但是如果我放类似

的东西
d =    {
      "name=": "",
      "\n": ",",
       re.compile(r'\s*NewName='): ":"}

我收到以下错误

TypeError: replace() 参数 1 必须是 str,而不是 re.Pattern

然后我尝试使用 re.sub 来处理正则表达式,但现在,它根本没有做任何事情(程序运行,但文件中没有修改):

for line in "test.txt":
    line = re.sub(r'\s*NewName=',":","test.txt")

提前感谢您的帮助

【问题讨论】:

    标签: regex python-3.x replace


    【解决方案1】:

    使用正则表达式。

    例如:

    import re
    
    res = {}
    with open(filename) as infile:
        for line in infile:                                   #Iterate Each line
            k, v = re.findall(r'=\"(.*?)\"', line.strip())    #Get Key-Value --> Get string in Quotes
            res[k] = v                                        #Form output
    print(res)
    

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 2019-04-17
      • 2018-07-13
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多