删除特定字符/标点符号以结束Python的URL列表

问题描述 投票:1回答:3

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

电流输出:

['https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u'', 'https://twitter.com/GVNyqWEu5u@#', 'https://twitter.com/GVNyqWEu5u"']

期望的输出:

['https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u']

您会理解,并非“当前输出”列表中的所有元素都有特殊字符/标点符号。任务是仅从拥有它们的列表元素中识别和删除字符/标点符号。

我正在使用以下正则表达式从Tweet文本中提取Twitter URL:lst = re.findall('(http.?://[^\s]+)', text)我可以在此步骤中删除URL末尾的特殊字符/标点符号吗?

完整代码:

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)
python regex python-3.x
3个回答
1
投票

假设特殊字符出现在字符串的末尾,您可以使用:

mydata = ['https://twitter.com/GVNyqWEu5u', "https://twitter.com/GVNyqWEu5u'", 'https://twitter.com/GVNyqWEu5u@#', 'https://twitter.com/GVNyqWEu5u"']
mydata = [re.sub('[^a-zA-Z0-9]+$','',item) for item in mydata]
print(mydata)

打印:

['https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u', 'https://twitter.com/GVNyqWEu5u']

0
投票

假设您的列表名为urls:

def remove_special_chars(url, char_list=None):
    if char_list is None:
        # Build your own default list here
        char_list = ['#', '%']
    for character in char_list:
        if url.endswith(character):
            return remove_special_chars(url[:-1], char_list)
    return url

urls = [remove_special_chars(url) for url in urls]

如果要删除一组特殊字符,只需更改默认值或传递正确的列表作为参数


0
投票

你可以尝试这个 -

lst = [re.sub('[=" ]$', '', i) for i in re.findall('(http.?://[^\s]+)', text)]

您可以根据需要在sub中添加更多要替换的字符

© www.soinside.com 2019 - 2024. All rights reserved.