Python删除包含 "l"的单词

标签 python file input output

我目前正在开发一个小程序。

该程序的目的是从文件中获取输入,编辑该文件以删除任何包含字母“l”的单词,然后将其输出到输出文件中。

我目前的代码可以工作,但是,它不会删除包含字母“l”的单词,而只是删除字母本身。

这是我的代码

def my_main(ifile_name, ofile_name):
    ifile_name = open(ifile_name, 'r')
    ofile_name = open(ofile_name, "w+")
    delete_list = ['l']
    for line in ifile_name:
        for word in delete_list:
            line = line.replace(word, "")
        ofile_name.write(line)
    ifile_name.close()
    ofile_name.close()

谢谢

更新

这是输入文件的样子:

The first line never changes. 
The second line was a bit much longer. 
The third line was short. 
The fourth line was nearly the longer line. 
The fifth was tiny. 
The sixth line is just one line more.
The seventh line was the last line of the original file.

当代码正确时,输出文件应如下所示

The first never changes. 
The second was a bit much. 
The third was short. 
The fourth was the. 
The fifth was tiny. 
The sixth is just one more.
The seventh was the of the.

最佳答案

在不查看您的文件是什么样的情况下,很难判断到底要使用什么,因此如果您可以更新问题,那就太好了

但目前您正在循环遍历每个字母而不是单词...使用 split() 将单词拆分为一个列表并更改该列表,然后将单词重新连接在一起以获得一个不包含包含您的字母的单词的字符串

words = ''
with open(ifile_name,"r") as file:
    for line in file:
        list_of_words = line.split(' ')
        for key, word in enumerate(list_of_words):
            if 'l' in word:
                list_of_words[key] = ''

        words += ' '.join(w for w in list_of_words if w != '')
        words += '\n'

with open(ofile_name, "w+") as file:
    file.write(words)

这样做的好处是您不会遇到任何空白问题。您将得到一个带有单个空格的常规字符串

编辑:正如评论中指出的,一种更好的方法来做到这一点(整个文件的非内存中)是内联执行它

with open(ifile_name,"r") as in_file, open(ofile_name, "w+") as out_file:
    for line in file:
        list_of_words = line.split(' ')
        for key, word in enumerate(list_of_words):
            if 'l' in word:
                list_of_words[key] = ''

        out_file.write(' '.join(w for w in list_of_words if w != ''))

关于Python删除包含 "l"的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33961749/

相关文章:

python - 如何在不手动设置 FLASK_APP 的情况下通过 flask run 或自定义命令运行 Flask 应用程序

ruby-on-rails - Ruby on Rails PaperClip - 如何将文件存储在 S3 或公共(public)文件夹以外的其他位置

c - 用 C 中的 fgets 覆盖我的数组

android - 打开设置屏幕以激活输入法

python - Django 保存方法静默失败

python - Masonite - AttributeError > 'str' 对象没有属性 'filename'

javascript - 在 jquery 中获取输入类型文件的 event.result

c - 在C中如何同时检测输入是字符还是整数?

Javascript - 像谷歌文档一样检测汉字输入

python - 无需更改 Python 和 Ruby 代码即可进行日志记录