在计算文件中的单词时,从单词的开头和结尾删除特殊字符

时间:2016-04-20 10:31:40

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

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

例如 -

;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))

4 个答案:

答案 0 :(得分:1)

使用re.sub

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

DEMO

答案 1 :(得分:0)

您可以编写一个查看字符是否有效的函数,然后使用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

答案 2 :(得分:0)

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

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!

答案 3 :(得分:0)

这是对我有用的代码     def removefromstart(x):
    ...我在[&#39;:&#39;,&#39;!&#39;,&#39;?&#39;,&#39;。&#39;,&#39 ;)&#39;&#39;(&#39;&#39 ;;&#39;&#39;&#39]:
    ...如果x.startswith(i):
    ... token = x.replace(i,&#39;&#39;)
    ...返回令牌
    ...返回x
    ......

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