【问题标题】:Update a text file with ( new words+ \n ) after the words is appended into a list将单词附加到列表后,使用 ( new words+ \n ) 更新文本文件
【发布时间】:2016-01-30 00:12:27
【问题描述】:

我有这个问题,我期待看到您的积极回答和解决方案。 代码如下:当程序在文本拆分后检测到拼写错误的单词时 它将每个拼写错误的单词附加到列表中 [a] 现在我的问题是,我怎样才能将拼写错误的单词写入(更新)到字典中,以使字典中的每一行只包含一个单词。到目前为止,我已经尝试过,它只写入当前插入并删除以前的记录。任何帮助表示赞赏(谢谢)

  def onaddbutton(self,event):
    os.chdir('d:/KKSC')
    dic = getDic()
    print dic[0], dic[1], dic[2]
    text = tokenize_editor_text(self.controlz.GetValue())     
    a = []
    for word in text:
        if word not in dic:
            misspelled = word
            a.append(misspelled)
            f= (misspelled)
            with open('test.text', encoding='utf-8', mode='w') as f:
            f.write(misspelled)
            f.write('\n')
            f.seek(0)
            print(repr(f.readline()[:1]))

【问题讨论】:

  • 请更正代码的缩进。当前版本存在语法错误。

标签: python python-2.7 python-3.x wxpython


【解决方案1】:

请更新您的缩进。

你的问题是你用 mode="w" 打开文件。尝试使用 mode="a" 代替追加。

另外,seek(0) 会将文件中的当前位置移动到第一行第一列。这似乎不是你想要的。摆脱那条线。

【讨论】:

  • 打开追加然后寻找文件的开头是结束乱码文件的好方法。
【解决方案2】:

以下是文件访问模式的列表:

"r" - 从文本文件中读取,如果不存在,python 会报错

"w" - 写入文本文件。如果它存在,它的内容将被覆盖。如果不是,则创建

"a" - 附加到文本文件,新数据附加到它。如果它不存在,则创建它

"w+" - 写入和读取文本文件。内容被覆盖或创建

"r+" - 读取和写入文本文件。找不到就投诉

"a+" - 附加到文本文件并从中读取。

在您的代码中,您编写了“open('test.text', encoding='utf-8', mode='w')”

如果您查看我在“w”写入并覆盖其内容之前创建的列表...但是要添加到列表中,如果您还想阅读它,您将需要“a”或“a+”。

所以要附加(添加到它的内容)到一个文本文件:

Text_file = open("Text file", "a")

因此,如果我们进行这些更改,您的程序现在将如下所示:

def onaddbutton(self,event):
       os.chdir('d:/KKSC')
       dic = getDic()
       print dic[0], dic[1], dic[2]
       text = tokenize_editor_text(self.controlz.GetValue())     
       a = []
       for word in text:
           if word not in dic:
               misspelled = word
               a.append(misspelled)
               f= (misspelled)
               with open('test.text', 'utf-8', 'a+') as f:
               f.append(misspelled\n)
        print(repr(f.readline()[:1]))

文本文件的其他一些内容...

Text_file.close()               # Closes the text file so you can open it again
Text_file.read()                # Reads all lines in a text file
Text_file.readlines(**X**)      # Reads 'x' number of lines

而且它们总是一个字符串......并且整理你可以做的文本文件......

Dictionary = Text_file.read() # reads all lines in text file 
Dictionary = sort(Dictionary)
Text_file.close() # Closes the text file.
Text_file = open("Text file.txt", "w") #Opens text file and overwrites what's in it
Text_file.write(Dictionary) # Writes ordered text into file.

应该按字母顺序排列它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2014-04-12
    相关资源
    最近更新 更多