- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
试图从单词列表中删除标点符号。 python 编程的新手,所以如果有人可以提供帮助,那就太好了。其目的是用于电子邮件垃圾邮件分类。以前我在检查标点符号是否存在后加入了单词,但这给了我单个字符而不是整个单词。更改它以获取单词后,这就是我在下面的内容,因此现在尝试删除标点符号,因为与以前的工作方式不同。
import os
import string
from collections import Counter
from os import listdir # return all files and folders in the directory
import nltk
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import pandas as pd
from nltk import WordNetLemmatizer
from nltk.corpus import stopwords
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
# used for importing the lingspam dataset
def importLingspamDataset(dir):
allEmails = [] # for storing the emails once read
fileNames = []
for file in listdir(dir):
f = open((dir + '/' + file), "r") # used for opening the file in read only format
fileNames.append(file)
allEmails.append(f.read()) # appends the read emails to the emails array
f.close()
return allEmails, fileNames
def importEnronDataset(dir):
allEmails = [] # for storing the emails once read
fileNames = []
for file in listdir(dir):
f = open((dir + '/' + file), "r") # used for opening the file in read only format
fileNames.append(file)
allEmails.append(f.read()) # appends the read emails to the emails array
f.close()
return allEmails, fileNames
# used to remove punctuation from the emails as this is of no use for detecting spam
def removePunctuation(cleanedEmails):
punc = set(string.punctuation)
for word, line in enumerate(cleanedEmails):
words = line.split()
x = [''.join(c for c in words if c not in string.punctuation)]
allWords = []
allWords += x
return allWords
# used to remove stopwords i.e. words of no use in detecting spam
def removeStopwords(cleanedEmails):
removeWords = set(stopwords.words('english')) # sets all the stopwords to be removed
for stopw in removeWords: # for each word in remove words
if stopw not in removeWords: # if the word is not in the stopwords to be removed
cleanedEmails.append(stopw) # add this word to the cleaned emails
return(cleanedEmails)
# funtion to return words to its root form - allows simplicity
def lemmatizeEmails(cleanedEmails):
lemma = WordNetLemmatizer() # to be used for returning each word to its root form
lemmaEmails = [lemma.lemmatize(i) for i in cleanedEmails] # lemmatize each word in the cleaned emails
return lemmaEmails
# function to allow a systematic process of elimating the undesired elements within the emails
def cleanAllEmails(cleanedEmails):
cleanPunc = removePunctuation(cleanedEmails)
cleanStop = removeStopwords(cleanPunc)
cleanLemma = lemmatizeEmails(cleanStop)
return cleanLemma
def createDictionary(email):
allWords = []
allWords.extend(email)
dictionary = Counter(allWords)
dictionary.most_common(3000)
word_cloud = WordCloud(width=400, height=400, background_color='white',
min_font_size=12).generate_from_frequencies(dictionary)
plt.imshow(word_cloud)
plt.axis("off")
plt.margins(x=0, y=0)
plt.show()
word_cloud.to_file('test1.png')
def featureExtraction(email):
emailFiles = []
emailFiles.extend(email)
featureMatrix = np.zeros((len(emailFiles), 3000))
def classifyLingspamDataset(email):
classifications = []
for name in email:
classifications.append("spmsg" in name)
return classifications
# Lingspam dataset
trainingDataLingspam, trainingLingspamFilename = importLingspamDataset("spam-non-spam-dataset/train-mails") # extract the training emails from the dataset
#testingDataLingspam, testingLingspamFilename = importLingspamDataset("spam-non-spam-dataset/test-mails") # extract the testing emails from the dataset
trainingDataLingspamClean = cleanAllEmails(trainingDataLingspam)
#testingDataLingspamClean = cleanAllEmails(testingDataLingspam)
#trainClassifyLingspam = classifyLingspamDataset(trainingDataLingspam)
#testClassifyLingspam = classifyLingspamDataset(testingDataLingspam)
trainDictionary = createDictionary(trainingDataLingspamClean)
#createDictionary(testingDataLingspamClean)
#trainingDataEnron, trainingEnronFilename = importEnronDataset("spam-non-spam-dataset-enron/bigEmailDump/training/")
最佳答案
根据您的问题,我假设您有一个电子邮件列表,您希望为每封电子邮件删除标点符号。此答案基于您发布的代码的第一次修订。
import string
def removePunctuation(emails):
# I am using a list comprehension here to iterate over the emails.
# For each iteration, translate the email to remove the punctuation marks.
# Translate only allows a translation table as an argument.
# This is why str.maketrans is used to create the translation table.
cleaned_emails = [email.translate(str.maketrans('', '', string.punctuation))
for email in emails]
return cleaned_emails
if __name__ == '__main__':
# Assuming cleanedEmails is a list of emails,
# I am substituting cleanedEmails with emails.
# I used cleanedEmails as the result.
emails = ["This is a, test!", "This is another#@! \ntest"]
cleaned_emails = removePunctuation(emails)
print(cleaned_emails)
input: ["This is a, test!", "This is another#@! \ntest"]
output: ['This is a test', 'This is another \ntest']
关于python删除标点符号电子邮件垃圾邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62448491/
我想将字符串拆分为列表中的单独句子。 例子: string = "Hey! How are you today? I am fine." 输出应该是: ["Hey!", "How are you to
好吧,这是我第一次发帖,所以如果我有任何错误,请多多包涵。长话短说,我得到了一个字符串数组,我的目标是计算字符串的唯一单词数并从数组中删除所有标点符号。 public static HashMap u
我正在尝试为自然语言解析器返回的词性标签和其他标签创建可区分的联合。 在 C#/Java 中通常使用字符串或枚举来表示它们,但在 F# 中似乎更适合区分联合,因为它们是不同的只读值。 在语言引用中,我
我正在处理 go/golang,尝试编写需要字符串和种子的代码。它应该返回一个打乱的字符串,其中单词中的第一个和最后一个字母、标点符号和数字保持不变。 示例: my name is Nikki. My
这个问题在这里已经有了答案: How can I use "." as the delimiter with String.split() in java [duplicate] (8 个答案) 关
我需要一种方法来使用包含省份缩写、全名和地区的词典,而不必为安大略省的每个可能的拼写错误添加条目。表如下: state |name | territory ============
我需要能够仅使用 C++ 字符串才能更改下面的输入段落。我遇到的问题是,当我在末尾拉出带有标点符号的东西时,例如“programs-”,它会将它作为“programs-”拉入我的数组,而不是分别将“p
我编写了一个函数来删除停用词和标记化,如下所示: def process(text, tokenizer=TweetTokenizer(), stopwords=[]): text =
df <- structure(list(`a a` = 1:3, `a b` = 2:4), .Names = c("a a", "a b" ), row.names = c(NA, -3L), c
我正在尝试使用javascript制作一个回文程序,即使字符串有标点符号和空格,它也会通过TRUE或FALSE显示字符串是否是回文(前女士,我是亚当)。但每次我输入一个字符串时,无论字符串是什么,我都
删除选择性连字符 import pandas as pd s = pd.Series(['do not-remove this-hyphen but remove-all of these-hyphe
在 Web 表单条目中,我们看到使用了奇怪的字符,例如: '(windows 1252 编码) 或 ðŸ'•(表情符号) 或 |(不知道,但认为它是 windows 1252) 对于其中一些,我可以使
从字符串中过滤掉所有 UTF-8 标点字符和符号(如✀✁✂✃✄✅✆✇✈等)的最佳和最有效方法是什么。简单地过滤掉所有不在 a-z、A-Z 和 0-9 中的字符不是一种选择,因为我想保留来自其他语言的字
Ruby 中是否有识别 Unicode 标点符号(例如,",-)的正则表达式? 最佳答案 你可以使用这个: /[[:punct:]]/ 有关更多信息,请查看 Regexp class .您也可以在此
我正在尝试创建一个 LPeg 模式,该模式将匹配 UTF-8 编码输入中的任何 Unicode 标点符号。我想出了以下 Selene Unicode 和 LPeg 的结合: local unicode
我正在编写一个Python代码来从输入文件中提取所有URL,其中包含来自Twitter(推文)的内容或文本。然而,在这样做时,我意识到在 python 列表中提取的几个 URL 在末尾有“特殊字符”或
我写emacs lisp代码如下: #!/usr/bin/emacs --script (setq input (read-minibuffer "please input your name:")
这是我的代码。用户将提供输入(任何字符串)而不是“这是一个测试。1 2 3 4 5”。 然后它将显示空格数、标点符号、数字和字母作为输出字符串。 #include #include using n
我正在尝试比较没有任何标点符号、空格、重音符号等的名称。目前我正在做以下事情: -(NSString*) prepareString:(NSString*)a { //remove any a
我正在使用 Ruby on Rails 3.1.0,我想知道如何在 YAML 文件中正确声明冒号(标点符号)。我试图通过在我的 config/locales/defaults/en.yml 文件 中添
我是一名优秀的程序员,十分优秀!