gpt4 book ai didi

Python删除包含 "l"的词

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:24 26 4
gpt4 key购买 nike

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

该程序的目的是从文件中获取输入,编辑文件以删除包含字母“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com