繁体   English   中英

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

[英]Remove special characters from the start and end of a word while counting the words in a file

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

例如 -

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

使用re.sub

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

演示

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

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

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!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM