【发布时间】:2016-03-01 21:55:28
【问题描述】:
我目前正在开发一个小程序。
该程序的目的是从文件中获取输入,编辑文件以删除包含字母“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.
【问题讨论】:
-
你需要分割空格,然后使用正则表达式将字母与单词匹配,如果是大小写则替换为空字符串
-
它不起作用,因为您将 l 替换为空。这意味着您的 delete_list 变为空。您需要将替换与您的 ifile_name 一起使用,而不是与 delete_list 一起使用。因此,您的 ifile_name 写为空。
-
文件有多大?能完全融入记忆吗?
-
@RNar 要删除的单词包含字母
'L'小写'l'看起来像大写'i' -
它带有字母“l”的单词与“L”的小版本一样。你可能把它误认为是字母“i”? :)