python替换;如果行以关键字开头,则替换为

2024-10-03 02:40:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,包含数千个条目,例如:

@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}
}

我将把关键字字段中的分号替换为逗号。但仅在“关键字”字段中-其他字段应保持不变:

^{pr2}$

我不是一个程序员,也许下面的代码片段是一个很好的起点,如果有人能完成我将非常感激。在

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),那么它会创建一个包含关键字的新文件。 如何使用同一个文件,并且只将分号替换为关键字行中的逗号?在


Tags: 代码line关键字outfilekeywordswritingreprder
3条回答

使用pyparsing

注意:这是一种方法,但大脑并没有处于解析模式-所以这是一个想法而不是一个正确的答案。。。这当然需要一些工作,但可能是正确的方向。。。在

一个使用pyparsing的有点混乱的例子。。。(如果使用@INBOOK和wotsit进行检查和解析,可能会更好,但无论如何……)

from pyparsing import *

keywords = originalTextFor(Keyword('keywords') + '=')
values = delimitedList(Regex('[^;}]+'), ';')
values.setParseAction(lambda L: ', '.join(L))

其中text是您的示例:

^{pr2}$
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() 

像这样的东西对单行线有效。在

if line.strip().startswith('keywords'):
    line = line.replace(';',',')
outfile.write(line) 

但是,如果关键字在实际的文本文件中跨越多行,则无法完成任务。在

相关问题 更多 >