繁体   English   中英

Python:使用其他令牌文件替换源文本文件中的单词

[英]Python :Replace words in source text file using other token file

我正在尝试替换源文件中的单词,引用令牌文件联系详细信息以用新单词替换旧单词。

数据正在被替换,但代码同时给出了原始数据和转换后的数据。 有人可以帮助解决这个问题。 以下是详细信息

输入文件布局:

SourceID|Organization|NPI|HIN  
1|ABC Hosp|12345|98765  
3|LMN Pharm|1234567|767654  

令牌文件布局:

Hosp,Hospital  
Pharm,Pharmacy  

当前 Output:

SourceID|Organization|NPI|HIN  
SourceID|Organization|NPI|HIN  
1|ABC Hospital|12345|98765  
1|ABC Hosp|12345|98765  
3|LMN Pharm|1234567|767654  
3|LMN Pharmacy|1234567|767654  

预期 Output:

SourceID|Organization|NPI|HIN  
1|ABC Hospital|12345|98765  
3|LMN Pharmacy|1234567|767654  

使用的代码:

import sys

Token = [i.strip().split(',') for i in open('TokenFile.csv')]  
InitialValue=int(sys.argv[1])  
InitialValue -=1  
NextVal=InitialValue+1  

with open('TokenizedOutput.txt', 'w') as out:    
with open('SourceFile.csv', 'r') as infile :  
  
  for line in infile:  
      Tokenization=line.split('|')[InitialValue]  
  
      BeforeAttri='|'.join(line.split('|')[0:InitialValue])  
      AfterAttri='|'.join(line.split('|')[NextVal:])  
     
  for oldword, newword in Token:  
     line = Tokenization.replace(oldword, newword)  
     CompValue=BeforeAttri+'|'+line+'|'+AfterAttri  
     print(CompValue)  
     out.write(CompValue)  
  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM