Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-从文本文件中删除单词或匹配字符串_Python - Fatal编程技术网

Python-从文本文件中删除单词或匹配字符串

Python-从文本文件中删除单词或匹配字符串,python,Python,我试图从一个文本文件中删除一个单词,并找到一个似乎有效的代码 但是,它不匹配一个确切的单词,而是删除所有匹配的字母 fin = open("input.txt") fout = open("output.txt", "w+") delete_list = input('delete : ') for line in fin: for word in delete_list: line = line.replace(word, '') fout.write(line

我试图从一个文本文件中删除一个单词,并找到一个似乎有效的代码

但是,它不匹配一个确切的单词,而是删除所有匹配的字母

fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = input('delete : ')
for line in fin:
    for word in delete_list:
        line = line.replace(word, '')
    fout.write(line)
fin.close()
fout.close()
print ('done')
input.txt

http://www.google.co.ma
google.com.mm
https://google.mn
www.google.com.mt
尝试删除http://(仅限)的结果如下-

output.txt

www.google.co.ma
google.com.mm
sgoogle.mn
www.google.com.m

让我们看看这里发生了什么:

  • 调用
    input
    ,它返回一个字符串“http://”。将其分配给变量
    delete\u list
  • 您可以使用
    for
    循环来遍历
    delete\u列表。但请注意:
    delete\u list
    是一个字符串,而不是列表。当您使用
    for
    循环遍历字符串时,它将遍历字符串的字母
  • 你仔细检查每个字母,并将其从行中删除
  • 要解决此问题,您可以做三件事:

  • 更改
    delete_-list
    的分配以分配给单个元素列表:
    delete_-list=[输入(“要删除的单词”)]

  • 重命名
    delete\u列表
    以更准确地反映其真实值,例如
    word\u to\u delete
    ,然后不要对
    循环使用
    ,只需执行
    行。直接替换(word\u to\u delete,)

  • 使用循环从用户处获取单词列表


  • 希望能把事情弄清楚

    我刚开始编写代码,所以不知道这个解决方案看起来有多难看,但是re模块看起来不错

    from re import sub
    with open('test.txt') as f:
        file = f.read().split('\n')
    for i in range(len(file)):
        file[i] = sub(r'http[s]?://', '', file[i])
    #print(file)
    with open('test1.txt', 'w') as f1:
        f1.writelines(["%s\n" % item  for item in file])
    
    或者,如果您不想使用re模块,可以使用if语句

    with open('test.txt') as f:
        file = f.read().split('\n')
    for i in range(len(file)):
        if file[i].startswith('https://'):
            link = file[i]
            file[i] = link[8:]
        elif file[i].startswith('http://'):
            link = file[i]
            file[i] = link[7:]
    #print(file)
    with open('test1.txt', 'w') as f1:
        f1.writelines(["%s\n" % item  for item in file])