【问题标题】:Remove special characters from the start and end of a word while counting the words in a file在计算文件中的单词时从单词的开头和结尾删除特殊字符
【发布时间】:2016-08-12 23:18:51
【问题描述】:

我需要对一个巨大的文本文件中的单词进行计数,但在此之前,我必须以特定的方式清理特殊字符的文件。

例如——

;xyz        -->      xyz      
xyz:        -->     xyz          
xyz!)       -->     xyz!

我正在使用 flatMap() 来分割空间上的所有单词。然后我试图删除不起作用的特殊字符。请帮忙!

这是我正在使用的代码 ---

要删除的字符是 - : ; ! ? ( ) .

   >>> input = sc.textFile("file:///home/<...>/Downloads/file.txt")
   >>> input2 = input.flatMap(lambda x: x.split())
   >>> def remove(x):
           if x.endsWith(':'):
                x.replace(':','')
                return x
           elif x.endsWith('.'):
               x.replace('.','')
               return x

。 .

      >>> input3 = input2.map(lambda x: remove(x))

【问题讨论】:

  • 为什么它不起作用?请发布您尝试过的内容。
  • 在第三个例子中“!”字符不是特殊字符?
  • 你能定义什么是特殊字符吗?
  • 要删除的字符是 - : ; ! ? ( ) 。 input = sc.textFile("file:///home/<...>/Downloads/file.txt") >>> input2 = input.flatMap(lambda x: x.split()) >>> def remove (x): if x.endsWith(':')==true: x.replace(':','') return x elif x.endsWith('.')==true: x.replace('.' ,'') 返回 x 。 . >>> input3 = input2.filter(lambda x: remove(x))

标签: python regex special-characters pyspark word-count


【解决方案1】:

使用re.sub

re.sub(r'(?<!\S)[^\s\w]+|[^\s\w]+(?!\S)', '', f.read())

DEMO

【讨论】:

    【解决方案2】:

    你可以写一个函数来判断一个字符是否有效,然后使用filter()

    def is_valid(char):
        return char.isalpha() or char in "!,." # Whatever extras you want to include
    
    new_string = ''.join(filter(is_valid, old_string)) # No need to ''.join() in Python 2
    

    【讨论】:

      【解决方案3】:

      尝试获得正则表达式的帮助:

      import re
      
      with open('input.txt','r') as fp:
          rx = "[;:\)]+"
          for line in fp:
              data = re.sub(rx, "", line.strip())
              print(data)
      

      上面的代码将逐行读取文件并发出经过净化的内容。根据文件的内容,它将打印:

      xyz
      xyz
      xyz!
      

      【讨论】:

        【解决方案4】:

        这是对我有用的代码-
        def removefromstart(x):
        ... for i in [':','!','?','.',')','(',';',',']:
        ...如果 x.startswith(i):
        ... token = x.replace(i,'')
        ...返回令牌
        ...返回 x
        ...

        def removefromend(x):  
        ...          for i in [':','!','?','.',')','(',';',',']:  
        ...                  if x.endswith(i):  
        ...                          token = x.replace(i,'')  
        ...                          return token  
        ...         return x
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-19
          相关资源
          最近更新 更多