簡體   English   中英

如何在 re.sub 中正確使用變量名

[英]How do I use a variable name correctly in re.sub

我是一個沮喪的 Python 新手。 我試圖不明白為什么我的代碼不會在文本文件的以下行中的分類值(SSLKT6_7.6.1)之后插入選項卡:

支持/知識中心/cs/SSLKT6_7.6.1/com.ibm.mam.doc/gp_finmgr/c_processes.html

支持/知識中心/de/SSLKT6_7.6.1/com.ibm.mam.doc/overview/c_new_config.html

代碼中的注釋行確實在“支持/知識中心/”之后進入了一個選項卡

謝謝你。

print ("Enter taxonomy: ")

taxonomy  = input( "> " )

with open( fileToSearch, "r+" ) as file:
  for line in fileinput.input( fileToSearch ):
  string4=line

  #result = re.sub('(knowledgecenter/)(.*?/' + re.escape(taxonomy) + ')', r'\1\t\2', line)

  result1 = re.sub('(knowledgecenter/)''(' + re.escape(taxonomy) + ')', r'\1\t\2', line)

 file.write(result1)

 fileinput.close

如果"SSLKT6_7.6.1"始終是地址的第四個元素,您可以使用str.split()方法通過正斜杠拆分地址。

將選項卡連接到列表的第四個元素(在索引3處) ,並使用str.join()方法通過斜杠加入列表:

strings = ["support/knowledgecenter/ cs/SSLKT6_7.6.1/com.ibm.mam.doc/gp_finmgr/c_processes.html", "support/knowledgecenter/ de/SSLKT6_7.6.1/com.ibm.mam.doc/overview/c_new_config.html"]
for s in strings:
    s = s.split("/")
    s[3] += "\t"
    print("/".join(s))

Output:

support/knowledgecenter/ cs/SSLKT6_7.6.1    /com.ibm.mam.doc/gp_finmgr/c_processes.html
support/knowledgecenter/ de/SSLKT6_7.6.1    /com.ibm.mam.doc/overview/c_new_config.html

如果"SSLKT6_7.6.1"之前的元素個數未知,可以使用list.index()方法找到"knowledgecenter"元素的索引,返回的索引加2 ,根據你的結構判斷您的正則表達式模式,這將返回"SSLKT6_7.6.1"的索引:

strings = ["support/knowledgecenter/ cs/SSLKT6_7.6.1/com.ibm.mam.doc/gp_finmgr/c_processes.html", "support/knowledgecenter/ de/SSLKT6_7.6.1/com.ibm.mam.doc/overview/c_new_config.html"]
for s in strings:
    s = s.split("/")
    s[s.index("knowledgecenter") + 2] += "\t"
    print("/".join(s))

Output:

support/knowledgecenter/ cs/SSLKT6_7.6.1    /com.ibm.mam.doc/gp_finmgr/c_processes.html
support/knowledgecenter/ de/SSLKT6_7.6.1    /com.ibm.mam.doc/overview/c_new_config.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM