【发布时间】:2020-06-11 08:13:24
【问题描述】:
在之前的数据集中,我已经在 csv 文件中进行了文本预处理,所以我这样做了
df = pd.read_csv('dataset.csv', dtype=str).apply(lambda x: x.astype(str).str.lower())
#open and lower casing all the data
#DELETE URL (HTTPS/HTTP)
df['DEL_URL'] = df['text'].apply(lambda x: re.split('https:\/\/.*|http:\/\/.*', str(x))[0])
#delete all the text in the columns called 'text' that have https://(anything) and delete all the text that have http://(anything)
df['DEL_URL'] = df['DEL_URL'].apply(lambda x: re.split('pic.tw*', str(x))[0])
#delete all the text in the columns 'DEL_URL' that have pic.tw(anything) because i have text that have pic.twitter sometimes
我在 csv 中作为输入的数据集是:
1. test this is my test https:///testing.com
2. test this is my test pic.twitter:///testing.com
output :
1. test this is my test
2. test this is my test
现在,我想在输入文本上使用小写字母并删除上面的 url,而不将其保存为 csv,所以我有这个代码来预测分类器并做一些特征选择 我运行代码,然后输入文本“测试这是我的测试https:///testing.compic.twitter/xxd123”
import re
##class
class prepro():
def __init__(self):
pass
def text_pre(self,new_doc):
lower_case = docs_new.lower()
#print("lowercase: ",lower_case) #work fine it give me (test this is my test https:///testing.com pic.twitter/xxd123)
del_url = re.split('https:\/\/.*|http:\/\/.*'," ",lower_case)
print("delete https or http: ",del_url)
#output ['test this is my test ', ''] something wrong with that
del_url2 = re.split('pic.tw*',del_url) #error
print ('del url 2: ',del_url2)#error
#output error
cs = prepro()
new_doc = input('input text: ')
#input a text example (test this is my test https:///testing.com)
process = cs.text_pre(new_doc)
x_newtfidf = tfidf.transform(process)
selectionfeature= seleksi.transform(x_newtfidf)
predicted = classifier.predict(selectionfeature)
print(predicted)
第一个问题为什么 del_rul 给我输出 ['测试这是我的测试','']我只希望像['测试这是我的测试'] 那为什么 del_url2 给我错误
Traceback (most recent call last):
File "C:\Users\xd\OneDrive\Desktop\something\filename.py", line 180, in <module>
proses = process.text_pre(new_doc)
File "C:\Users\xd\OneDrive\Desktop\something\filename.py", line 154, in low
del_url2 = re.split('pic.tw*',[del_url])
File "E:\anaconda3\lib\re.py", line 213, in split
return _compile(pattern, flags).split(string, maxsplit)
TypeError: expected string or bytes-like object```
【问题讨论】:
-
del_url是一个列表。如果你将它作为第二个参数传递给re.split,你会得到一个 TypeError。 -
也许替换函数re.sub 会是这个用例的更好选择。您可以通过用空字符串替换它们来简单地删除 url,例如
del_url = re.sub(r'https?://.*', '', lower_case).
标签: python python-3.x regex pandas