替换文件中的单词

时间:2018-12-13 11:15:33

标签: python file file-handling

badcontent = []
filebadword = "badwords.txt"
with open(filebadword, 'r') as read_file:
  badcontent = read_file.readlines()

goodcontent = []
filegoodword = "goodword.txt"
with open(filegoodword, 'r') as read_file:
  goodcontent = read_file.readlines()


msgfile = "msg.txt"
file = open(msgfile, "r")
for word in file:
  if word in badcontent:
    file = file.write(word.replace([badcontent],[goodconent]))
    print(file.readline())
    file.close()
  elif():
    print(file.readline())
    file.close()

我想尝试用友好的词替换味精文件中的“不合适”词。

3 个答案:

答案 0 :(得分:0)

Python具有string.replace(old, new)方法。您正在尝试用列表替换一个单词,这将导致错误。这是一个示例,您应如何阅读全文:

from random import randint

with open("text_msg_file.txt", 'rb') as f:
    lines = f.readlines()

# Text file containing bad words, assume only one word/line
with open("badcontent.txt", 'rb') as f:
    badcontent = f.readlines()

# Text file containing good words, assume only one word/line
with open("goodcontent.txt", 'rb') as f:
    goodcontent = f.readlines()

# Strip new line character from words
lines = [word.strip("\n") for word in lines]
badcontent = [word.strip("\n") for word in badcontent]
goodcontent = [word.strip("\n") for word in goodcontent]

for i in range(len(lines)):
    line = lines[i]
    # List of words on single line. Line splitted from whitespaces
    words = line.split(" ")
    # Loop through all words
    for j in range(len(words)):
        # Get random integer for index
        index = randint(0, len(goodcontent))
        if words[j] in badcontent:
            # Replace bad word with a good word
            words[j] = goodcontent[index]
    # Join all words from a list into a string
    line = " ".join(words)
    # Put string back to list of lines
    lines[i] = line
# Join all lines back into one single text
new_text = "\n".join(lines)
with open("new_msg.txt", "wb") as f:
    f.write(new_text)

这会将替换单词的文本写入文件new_msg.txt。在Python 2.7中,对'rb'语句使用'wb'open来启用以二进制模式打开,因此代码更加健壮。对于Python 3,仅将'r''w'用于open语句。

答案 1 :(得分:0)

我不知道在您的不良和不良文件中它们是否仅是一个参数。 如果您没有字典,则无法进行更正。

dictionary={}
dictionary['****']='#######'
dictionary['inappropriate_word']='good'

new_file=''
for line in file:
    for word in line:
        if word in dictionary:
            new_file+=dictionary[word]
        else:
            new_file+=word
        new_file+=" "
    new_file+="\n"

dictionary={}
dictionary['****']='#######'
dictionary['inappropriate_word']='good'

l=open(file,"r").read()
for i in dictionary:
    l.replace(i,dictionary[i])
o=open("fileoutput.txt","w")
o.write(l)
o.close()

如果您有2个带单词的文件,则可以导入信息并将其存储在字典中

答案 2 :(得分:0)

尝试文本(非真实数据):

import shelve

class TextArgsCode:
    def __init__(self, function_codetext, text, programfile): #text = 'define'; replace by function_codetext[text]
        self.text = text
        self.function_codetext = function_codetext
        self.textfile = open(programfile, 'r').read()
        self.textfilewrite = open(programfile+'write.py', 'w')

    
    def textcode_newtext(self):
        for text in self.textfile.split('\n'):
            textwrite = text.replace(self.text, self.function_codetext[self.text])
            if len(textwrite) > 0:
              textwrite = '\n'+textwrite
              self.textfilewrite.write(textwrite)

            else:
              text = '\n'+text
              self.textfilewrite.write(text)
            
        self.textfilewrite.close()  
        return(None)
          





if __name__ == '__main__':
    textargsdata = shelve.open('sqldb.db')
    textargsdata = textargsdata['data']
    textargscode = TextArgsCode(textargsdata, 'define', 'test.py') #replace self.text = 'define' in test.py'
    textargscode.textcode()