Регулярные выражения в python / pandas вызывают странные символы конца строки - PullRequest
0 голосов
/ 16 октября 2018

Я только начинаю работать с Pandas и работаю над инструментом очистки домена.По сути, я хочу удалить все дочерние домены и просто сохранить основной домен + tld.

Ниже показано, как работает ipython для одного домена, но я борюсь с фреймом данных нескольких доменов.

Сценарий, кажется, работает, но регулярное выражение приводит к тому, что символы конца строки (как показано ниже) печатаются в конце домена (например, com \ n1 ')

Я не уверен, что этосимволы - я пробовал rstrip, но это не сработало.Кто-нибудь может посоветовать, что это за символы и как я могу от них избавиться, чтобы скрипт работал?

ВЫХОД

['0          graph', 'facebook', 'com\n1              news', 'bbc', 'co', 'uk\n2 

ОЖИДАЕМЫЙ ВЫХОД

Когда я запускаю то же самое в ipython, я получаю следующее - мне нужно, чтобы разделение было одинаковым при использовании столбца df.

In [12]: re.split(r'\.(?!\d)', (str('domain.domain.com')))
Out[12]: ['domain', 'domain', 'com']

INPUT

In [1]: import pandas as pd

In [2]: import re

In [3]: path = "Desktop/domains.csv"

In [4]: df = pd.read_csv(path, delimiter=',', header='infer')

In [5]: df
Out[5]: 
                     Domain
0        graph.facebook.com
1            news.bbc.co.uk
2  news.more.news.bbc.co.uk
3       profile.username.co
4           offers.o2.co.uk
5     subdomain.pyspark.org
6       uds.data.domain.net

In [7]: for index, row in df.iterrows():
   ...:     tld = ['co.uk', 'com', 'org', 'co', 'net']
   ...:     index = re.split(r'\.(?!\d)', (str(df.Domain)))
   ...:     print(index)
   ...:     if str(index[len(index)-2]).rstrip()+'.'+ str(index[len(index)-1]).rstrip() in tld:
   ...:         print(str(index[len(index)-3])+'.'+str(index[len(index)-2])+'.'+ str(index[len(index)-1]))
   ...:     elif str(index[len(index)-1]) in tld:
   ...:         print(str(index[len(index)-2])+'.'+ str(index[len(index)-1]))

ОБНОВЛЕНИЕ


Спасибо всем за помощь до сих пор.

Теперь ниже работает точно так, как и ожидалось, но результатывсе дублируются несколько раз.

Например, вы можете видеть, что Facebook.com был напечатан дважды в списке вывода, и я не могу понять, почему - кто-нибудь может посоветовать?

ВХОД

In [38]: for row in df.iterrows():
    ...:     tld = ['co.uk', 'com', 'org', 'co', 'net']
    ...:     index = df.Domain[df.Domain.str.strip().str.endswith(tuple(tld))].str.split('.').tolist()
    ...:     for x in index:
    ...:         if str(x[len(x)-2]).rstrip()+'.'+ str(x[len(x)-1]).rstrip() in tld:
    ...:             print(str(x[len(x)-3])+'.'+str(x[len(x)-2])+'.'+ str(x[len(x)-1]))
    ...:         elif str(x[len(x)-1]) in tld:
    ...:             print(str(x[len(x)-2])+'.'+ str(x[len(x)-1]))
    ...: 
    ...:                     
facebook.com
bbc.co.uk
bbc.co.uk
username.co
o2.co.uk
pyspark.org
domain.net
facebook.com

1 Ответ

0 голосов
/ 16 октября 2018

Вот рабочий код:

In [5]: import pandas as pd
In [6]: import re
#Define the path of the file & generate the dataframe from it
In [7]: path = "Desktop/domains.csv"
In [8]: df = pd.read_csv(path, delimiter=',', header='infer')
#Show the dataframe to validate input is correct
In [9]: df
Out[10]:
                     Domain
0        graph.facebook.com
1            news.bbc.co.uk
2  news.more.news.bbc.co.uk
3       profile.username.co
4           offers.o2.co.uk
5     subdomain.pyspark.org
6       uds.data.domain.net

#Iterate through the rows of the dataframe. If the domain ends with anything in the TLD list, then split the domains at the '.' into a list
In [11]: for row in df.iterrows():
    ...:     tld = ['co.uk', 'com', 'org', 'co', 'net']
    ...:     index = df.Domain[df.Domain.str.strip().str.endswith(tuple(tld))].str.split('.').tolist()
    ...:
#Now, let's look at the output of index. It's a list of lists. So, if we select index[1]. we will get  ['news', 'bbc', 'co', 'uk']
In [12]: index
Out[12]:
[['graph', 'facebook', 'com'],
 ['news', 'bbc', 'co', 'uk'],
 ['news', 'more', 'news', 'bbc', 'co', 'uk'],
 ['profile', 'username', 'co'],
 ['offers', 'o2', 'co', 'uk'],
 ['subdomain', 'pyspark', 'org'],
 ['uds', 'data', 'domain', 'net']]

#We therefore need to iterate through each item of the lists
#So, we need to go through index[0][0] (the sub lists - to see the breakdown of each domain)
#Now we take the length of the list e.g. graph, facebook, com = length of 3
#as it's a zero'd index, we need to start at 0 and hence a list with a length of 3, has a range of 0-2
#so first, we check, is the last but one character + the last character in the TLD list (e.g. co.uk)
#if yes, we take the last 3 elements of the list, to produce 'bbc.co.uk'
#if no, we go through and check the last character & see if its in the list (e.g. com)
#if it is, we print the last 2 characters (e.g. facebook.com)
    ...: for x in index:
    ...:     if str(x[len(x)-2]).rstrip()+'.'+ str(x[len(x)-1]).rstrip() in tld:
    ...:         print(str(x[len(x)-3])+'.'+str(x[len(x)-2])+'.'+ str(x[len(x)-1]))
    ...:     elif str(x[len(x)-1]) in tld:
    ...:         print(str(x[len(x)-2])+'.'+ str(x[len(x)-1]))
    ...:

#and here is the ouput
facebook.com
bbc.co.uk
bbc.co.uk
username.co
o2.co.uk
pyspark.org
domain.net
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...