【问题标题】:Remove every word that starts with a certain string删除以特定字符串开头的每个单词
【发布时间】:2020-12-12 16:49:36
【问题描述】:

我正在尝试删除文本文件中以某个字符串开头的每个单词。我不知道如何写入输出文件。

输入文件:

Lorem ipsum applePEAR
dolor appleBANANA sit 
appleORANGE amet, consectetur

所需的输出文件:

Lorem ipsum 
dolor sit
amet, consectetur

到目前为止我的方法:

with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        ls = line.split()
        for word in ls():
            if word.startswith("apple"):
                line.replace(word, "")
        fout.write(line)

我认为这种方法的问题是替换行拆分列表中的单词,而不是行本身。

检查 Stackoverflow,我发现这个问题类似于:using Python for deleting a specific line in a file,除了“nickname_to_delete”是一个以字符串开头的单词。

【问题讨论】:

  • replace 有拼写错误吗?
  • 刚刚更正了拼写错误,但仍然没有运气。

标签: python string list replace


【解决方案1】:

过滤器也可以使用

word="apple" 
with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        string_iterable = filter(lambda x:not(x.startswith(word)), line.strip().split())
        fout.write(" ".join(string_iterable))

【讨论】:

  • 如何替换以某个字符串开头的单词?
  • 对不起,我错过了苹果。*
【解决方案2】:

我已尽可能少地更新了您的代码:

with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        ls = line.split(" ")
        newline = []
        for word in ls:  # Don't call() the list
            if not word.startswith("apple"):
                newline.append(word)  # Append all words that don't start with apple.
        fout.write(" ".join(newline))  # Remake new line

请记住,替换正则表达式会更好,并且可以处理“newword,appleshake”:

import re

with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        fout.write(re.sub(r"\bapple\w+", "", line))

\w 仍然会影响标点符号,但您需要选择如何处理它。

【讨论】:

    【解决方案3】:

    有一些问题。

    • 你打电话给ls() - 应该只是ls
    • 调用 line.replace()(除了错字)不会修改 line 的内容 - 它只是返回一个新字符串,然后您将丢弃它
    • 原则上存在这样的风险,通过这种方式进行替换,您还会无意中删除部分其他单词 - 在“我喜欢菠萝和苹果”这一行中,“菠萝”中的“苹果”也会得到已删除(“我喜欢松树和”)。

    这是一个替代方案(注意限制:单词之间的空格量不会被保留)。

    with open(infile) as fin, open(outfile, "w+") as fout:
        for line in fin:
            ls = line.split()
            words = [word for word in ls if not word.startswith('apple')]
            line_out = ' '.join(words)
            fout.write(line_out + '\n')
    

    【讨论】:

      猜你喜欢
      • 2018-12-22
      • 1970-01-01
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 1970-01-01
      • 2015-04-28
      相关资源
      最近更新 更多