如何在PYTHON中浏览文件的单词?
我有一个.txt文件,我想浏览其中的文字。我有个问题,我需要在浏览单词之前去掉标点符号。我已经试过了,但它并没有去除标点符号如何在PYTHON中浏览文件的单词?,python,python-2.7,text,punctuation,Python,Python 2.7,Text,Punctuation,我有一个.txt文件,我想浏览其中的文字。我有个问题,我需要在浏览单词之前去掉标点符号。我已经试过了,但它并没有去除标点符号 file=open(file_name,"r") for word in file.read().strip(",;.:- '").split(): print word file.close() 当前方法的问题是.strip()并不能真正实现您想要的功能。它将删除前导字符和尾随字符(您希望删除文本中的字符),如果您希望指定除空白之外的字符,则这些字符需要位于
file=open(file_name,"r")
for word in file.read().strip(",;.:- '").split():
print word
file.close()
当前方法的问题是
.strip()
并不能真正实现您想要的功能。它将删除前导字符和尾随字符(您希望删除文本中的字符),如果您希望指定除空白之外的字符,则这些字符需要位于列表中
另一个问题是,还有更多潜在的标点符号(问号、感叹号、unicode省略号、em破折号)不会被列表过滤掉。相反,您可以使用string.parantion
来获取大量字符(请注意string.parantion
不包括一些非英语字符,因此其可行性可能取决于输入的来源):
一种更快的方法(如上所示)使用string.translate()
替换字符:
import string
text = text.translate(string.maketrans('', ''), string.punctuation)
在将单词存储在如下列表中后,我将使用
replace
函数删除标点符号:
with open(file_name,"r") as f_r:
words = []
for row in f_r:
words.append(row.split())
punctuation = [',', ';', '.', ':', '-']
words = [x.replace(y, '') for y in punctuation for x in words]
您可以尝试使用
re
模块:
import re
with open(file_name) as f:
for word in re.split('\W+', f.read()):
print word
有关更多详细信息,请参阅
编辑:对于非ASCII字符,前面的代码将忽略它们。在这种情况下,以下代码可能会有所帮助:
import re
with open(file_name) as f:
for word in re.compile('\W+', re.unicode).split(f.read().decode('utf8')):
print word
strip()
仅删除字符串开头或结尾处的字符。
所以split()
import string
with open(file_name, "rt") as finput:
for line in finput:
for word in line.split():
print word.strip(string.punctuation)
或者使用自然语言库,如nltk
:以下代码保留撇号和空格,如果需要,可以轻松修改以保留双引号。它通过使用基于string对象子类的转换表来工作。我认为代码相当容易理解。如有必要,可能会提高效率
class SpecialTable(str):
def __getitem__(self, chr):
if chr==32 or chr==39 or 48<=chr<=57 \
or 65<=chr<=90 or 97<=chr<=122:
return chr
else:
return None
specialTable = SpecialTable()
with open('temp2.txt') as inputText:
for line in inputText:
print (line)
convertedLine=line.translate(specialTable)
print (convertedLine)
print (convertedLine.split(' '))
是否要删除标点符号,然后写回文件?此外,这将仅从整个文件的开头和结尾删除这些字符,而不是单个单词。这样做是什么?split()
,然后再split()
(至少这会让你更接近目标)@Farhan.K我不想碰原始文件。我只想把单词分开,不加标点符号,这样你就必须迭代.works,但就内存效率而言,这是最糟糕的解决方案之一。也很难阅读。实际上所有这些都可以压缩在一行中。你读这篇文章真的有问题吗?
class SpecialTable(str):
def __getitem__(self, chr):
if chr==32 or chr==39 or 48<=chr<=57 \
or 65<=chr<=90 or 97<=chr<=122:
return chr
else:
return None
specialTable = SpecialTable()
with open('temp2.txt') as inputText:
for line in inputText:
print (line)
convertedLine=line.translate(specialTable)
print (convertedLine)
print (convertedLine.split(' '))
This! is _a_ single (i.e. 1) English sentence that won't cause any trouble, right?
This is a single ie 1 English sentence that won't cause any trouble right
['This', 'is', 'a', 'single', 'ie', '1', 'English', 'sentence', 'that', "won't", 'cause', 'any', 'trouble', 'right']
'nother one.
'nother one
["'nother", 'one']