600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python去掉标点 特殊符号_删除URL的Python列表末尾的特殊字符/标点符号

python去掉标点 特殊符号_删除URL的Python列表末尾的特殊字符/标点符号

时间:2021-11-07 11:17:58

相关推荐

python去掉标点 特殊符号_删除URL的Python列表末尾的特殊字符/标点符号

我正在编写一个Python代码,从一个输入文件中提取所有url,其中包含来自Twitter(Tweets)的内容或文本。然而,在这样做的时候,我意识到在python列表中提取的几个URL在结尾处有“特殊字符”或“标点符号”,因此我无法通过它们进一步解析来获得基本URL链接。我的问题是:“如何识别和删除列表中每个URL末尾的特殊字符”?在

电流输出:['/GVNyqWEu5u', '/GVNyqWEu5u'', '/GVNyqWEu5u@#', '/GVNyqWEu5u"']

期望输出:

^{pr2}$

您应该注意,不是“当前输出”列表中的所有元素都在末尾有特殊字符/标点符号。任务是识别并仅从拥有这些字符/标点的列表元素中删除这些字符/标点符号。在

我使用以下Regex从Tweet文本中提取twitter url:lst = re.findall('(http.?://[^\s]+)', text)

我是否可以删除此步骤末尾的特殊标点符号?在

完整代码:import urllib.request, urllib.parse, urllib.error

from bs4 import BeautifulSoup

from socket import timeout

import ssl

import re

import csv

ctx = ssl.create_default_context()

ctx.check_hostname = False

ctx.verify_mode = ssl.CERT_NONE

count = 0

file = "Test.CSV"

with open(file,'r', encoding='utf-8') as f, open('output_themes_1.csv', 'w', newline='', encoding='utf-8') as ofile:

next(f)

reader = csv.reader(f)

writer = csv.writer(ofile)

fir = 'S.No.', 'Article_Id', 'Validity', 'Content', 'Geography', 'URL'

writer.writerow(fir)

for line in reader:

count = count+1

text = line[5]

lst = re.findall('(http.?://[^\s]+)', text)

if not lst:

x = count, line[0], 'Empty List', text, line[8], line[6]

print (x)

writer.writerow(x)

else:

try:

for url in lst:

try:

html = urllib.request.urlopen(url, context=ctx, timeout=60).read()

#html = urllib.request.urlopen(urllib.parse.quote(url, errors='ignore'), context=ctx).read()

soup = BeautifulSoup(html, 'html.parser')

title = soup.title.string

str_title = str (title)

if 'Twitter' in str_title:

if len(lst) > 1: break

else: continue

else:

y = count, line[0], 'Parsed', str_title, line[8], url

print (y)

writer.writerow(y)

except UnicodeEncodeError as e:

b_url = url.encode('ascii', errors='ignore')

n_url = b_url.decode("utf-8")

try:

html = urllib.request.urlopen(n_url, context=ctx, timeout=90).read()

soup = BeautifulSoup(html, 'html.parser')

title = soup.title.string

str_title = str (title)

if 'Twitter' in str_title:

if len(lst) > 1: break

else: continue

else:

z = count, line[0], 'Parsed_2', str_title, line[8], url

print (z)

writer.writerow(z)

except Exception as e:

a = count, line[0], str(e), text, line[8], url

print (a)

writer.writerow(a)

except Exception as e:

b = count, line[0], str(e), text, line[8], url

print (b)

writer.writerow(b)

print ('Total Rows Analyzed:', count)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。