【问题标题】:Python read/writePython 读/写
【发布时间】:2013-12-08 14:34:25
【问题描述】:

我的程序必须读入一个多行的文本文件。然后它复制 相同的文本到输出文件,除了所有无用的单词,如“the”、“a”和“an”都被删除。有什么问题?

f=open("a.txt","r")
inp=f.readlines()
f.close()
out=open("a.txt","w")
stopList=['the','a','an']
for i in inp:
    if i in stopList:
        out.write(i)
out.close()

【问题讨论】:

  • "a.txt" 将具有初始+附加行,因为您不清除文件。不确定这是否重要。此外,您能否告诉我们问题的症状,即正在发生的事情而不是您希望发生的事情?
  • 您拥有文件中所有行的列表。您正在遍历列表,检查一行是否在 stopList 中,它只包含三个单词“the”、“a”、“an”。你不觉得这里有问题吗?

标签: python sorting file-io


【解决方案1】:

好了,用str.replace:

with open("a.txt","r") as fin, open("b.txt","w") as fout:
    stopList=['the','a','an']
    for line in fin:
        for useless in stopList:
            line = line.replace(useless+' ', '')
         fout.write(line)

如果您不想将整个文件存储到内存中,则需要将结果写入其他地方。但是如果你不介意,你可以重写它:

with open("a.txt","r") as fin, open("a.txt","w") as fout:
    stopList=['the','a','an']
    r = []
    for line in fin:
        for useless in stopList:
            line = line.replace(useless+' ', '')
        r.append(line)
    fout.writelines(r)

演示:

>>> line = 'the a, the b, the c'
>>> stopList=['the','a','an']
>>> for useless in stopList:
    line = line.replace(useless+' ', '')


>>> line
'a, b, c'

【讨论】:

  • @alKid 它复制一个元素三倍
  • “三乘一元素”是什么意思?
  • @alKid 例如,它会写 3 次单词“ABC”,例如“ABC ABC ABC”
  • 哦,哎呀!对于那个很抱歉。已更新。
【解决方案2】:

使用regular expression

import re

with open('a.txt') as f, open('b.txt','w') as out:
    stopList = ['the', 'a', 'an']
    pattern = '|'.join(r'\b{}\s+'.format(re.escape(word)) for word in stopList)
    pattern = re.compile(pattern, flags=re.I)
    out.writelines(pattern.sub('', line) for line in f)

# import shutil
# shutil.move('b.txt', 'a.txt')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多