我目前正在开发一个小程序。
该程序的目的是从文件中获取输入,编辑该文件以删除任何包含字母“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/