【问题标题】:Removing words from a file从文件中删除单词
【发布时间】:2012-10-22 16:46:14
【问题描述】:

我正在尝试获取常规文本文件并删除在单独文件(停用词)中标识的单词,该文件包含要删除的单词,由回车符(“\n”)分隔。

现在我正在将两个文件转换为列表,以便可以比较每个列表的元素。我让这个函数工作,但它不会删除我在停用词文件中指定的所有单词。非常感谢任何帮助。

def elimstops(file_str): #takes as input a string for the stopwords file location
  stop_f = open(file_str, 'r')
  stopw = stop_f.read()
  stopw = stopw.split('\n')
  text_file = open('sample.txt') #Opens the file whose stop words will be eliminated
  prime = text_file.read()
  prime = prime.split(' ') #Splits the string into a list separated by a space
  tot_str = "" #total string
  i = 0
  while i < (len(stopw)):
    if stopw[i] in prime:
      prime.remove(stopw[i]) #removes the stopword from the text
    else:
      pass
    i += 1
  # Creates a new string from the compilation of list elements 
  # with the stop words removed
  for v in prime:
    tot_str = tot_str + str(v) + " " 
  return tot_str

【问题讨论】:

    标签: python string list file-io python-3.x


    【解决方案1】:

    这是使用生成器表达式的替代解决方案。

    tot_str = ' '.join(word for word in prime if word not in stopw)
    

    为了提高效率,请使用stopw = set(stopw)stopw 转换为set

    如果 sample.txt 不仅仅是一个空格分隔的文件,您当前的方法可能会遇到问题,例如,如果您有带有标点符号的普通句子,那么在空格上拆分会将标点符号作为单词的一部分。要解决此问题,您可以使用 re 模块将字符串拆分为空格或标点符号:

    import re
    prime = re.split(r'\W+', text_file.read())
    

    【讨论】:

    • 我认为没有必要——他正在迭代 stopw 并从 prime 中删除元素
    • @SamMussmann 谢谢,我刚刚注意到了。用标点符号导致 OP 出现问题的理论编辑了我的答案。
    【解决方案2】:

    我不知道 python,但这里有一个通用的方法,即 O(n)+O(m) 时间 - 线性。

    1:将停用词文件中的所有单词添加到地图中。
    2:阅读您的常规文本文件并尝试将单词添加到列表中。 当您执行 #2 时,检查当前读取的单词是否在地图中,如果是跳过它,否则将其添加到列表中。

    最后,列表应该包含您需要的所有单词 - 您想要删除的单词。

    【讨论】:

      【解决方案3】:

      我认为你的问题是这一行:

          if stopw[i] in prime:
            prime.remove(stopw[i]) #removes the stopword from the text
      

      只会从prime 中删除第一次出现的stopw[i]。要解决此问题,您应该这样做:

          while stopw[i] in prime:
            prime.remove(stopw[i]) #removes the stopword from the text
      

      但是,这将运行得非常缓慢,因为in primeprime.remove 位都必须遍历素数。这意味着您最终将在字符串长度中获得quadratic 运行时间。如果你使用像 F.J.suggests 这样的生成器,你的运行时间将是线性的,这样会好很多。

      【讨论】:

        猜你喜欢
        • 2013-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多