[英]python replace ; with , if line starts with keyword
我有一個包含數千個條目的文本文件,例如:
@INBOOK{Abu-Lughod1991,
chapter = {Writing against culture},
pages = {137-162},
title = {Recapturing anthropology},
publisher = {School of American Research Press},
year = {1991},
editor = {Richard Fox},
author = {Abu-Lughod, Lila},
address = {Santa Fe /NM},
abstract = {Im Zusammenhang mit der Debatte um die writing culture fomuliert AL
eine feministische Kritik und zeigt, wie von dort doch Anregungen
für die Reflektion der Schreibweise und Repräsentation gekommen sind.*},
crossref = {Rabinow1986},
keywords = {Frauen; Feminismus; Erzählung als EG; Repräsentation; Roman; Schreibtechnik;
James Clifford; writing culture; Dialog;},
owner = {xko},
systematik1 = {Anth\theor\Ethnographie},
systematik2 = {Anth\theor\Text & Ges},
timestamp = {1995-12-02}
}
我將替換關鍵字-逗號中的所有分號。 但僅在關鍵字字段中-其他字段應保持不變:
keywords = {Frauen, Feminismus, Erzählung als EG, Repräsentation, Roman, Schreibtechnik, James Clifford, writing culture, Dialog,},
我不是程序員,也許以下代碼段是一個不錯的起點,如果有人能完成它,我將不勝感激。
outfile = open("literatur_comma.txt", "w")
for line in open("literatur_semicolon.txt", "r"):
if line # starts with "keywords" replace all semicolon with comma
outfile.write(line) # write in new file
outfile.close()
非常感謝!
編輯:感謝您的所有答案和代碼,太好了! 我的想法有誤,如果我使用代碼包裝器(帶有outfile),則會創建一個包含關鍵字的新文件。 我如何使用同一文件,並僅將分號替換為關鍵字行中的逗號?
這樣的事情只適用於一行。
if line.strip().startswith('keywords'):
line = line.replace(';',',')
outfile.write(line)
但是,如果關鍵字在您的實際文本文件中跨多行,則將無法完成工作。
outfile = open("literatur_comma.txt", "w")
for line in open("literatur_semicolon.txt", "r"):
if line.startswith('keywords'): # starts with "keywords" replace all semicolon with comma
outfile.write(line.replace(';',',')) # write in new file
outfile.close()
使用pyparsing
注意:這是執行此操作的一種方法,但是大腦不在解析模式下-因此這是一個主意,而不是一個正確的答案...它當然需要做一些工作,但很可能是正確的方向...
使用pyparsing
一個有點混亂的示例...(可能會更好一些,有一些@INBOOK和wotsit檢查和解析,但是無論如何...)
from pyparsing import *
keywords = originalTextFor(Keyword('keywords') + '=')
values = delimitedList(Regex('[^;}]+'), ';')
values.setParseAction(lambda L: ', '.join(L))
text
是您的示例:
>>> print values.transformString(text)
@INBOOK{Abu-Lughod1991,
chapter = {Writing against culture},
pages = {137-162},
title = {Recapturing anthropology},
publisher = {School of American Research Press},
year = {1991},
editor = {Richard Fox},
author = {Abu-Lughod, Lila},
address = {Santa Fe /NM},
abstract = {Im Zusammenhang mit der Debatte um die writing culture fomuliert AL
eine feministische Kritik und zeigt, wie von dort doch Anregungen
für die Reflektion der Schreibweise und Repräsentation gekommen sind.*},
crossref = {Rabinow1986},
keywords = {Frauen, Feminismus, Erzählung als EG, Repräsentation, Roman, Schreibtechnik, James Clifford, writing culture, Dialog;},
owner = {xko},
systematik1 = {Anth heor\Ethnographie},
systematik2 = {Anth heor\Text & Ges},
timestamp = {1995-12-02}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.