Python url字符串匹配

2024-10-03 04:35:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题如下。我有一个很长的网址列表,例如:

www.foo.com/davidbobmike1joe
www.foo.com/mikejoe2bobkarl
www.foo.com/joemikebob
www.foo.com/bobjoe

我需要将列表中的所有条目(url)相互比较,在这些url的子域中提取关键字(在本例中:david、joe、bob、mike、karl),并按频率排序。我一直在读一些关于nltk之类的库。然而,这里的问题是没有空格来独立标记每个单词。关于如何完成这项工作有什么建议吗?在


Tags: 子域comurl列表foowww条目关键字
2条回答

概述

您可以使用此代码提取姓名,并传递[david,bob,etc.]的列表:

Is there an easy way generate a probable list of words from an unspaced sentence in python?

然后使用collections.Counter得到频率。在

代码

from Bio import trie
import string
from collections import Counter


def get_trie(words):
    tr = trie.trie()
    for word in words:
        tr[word] = len(word)
    return tr

def get_trie_word(tr, s):
    for end in reversed(range(len(s))):
        word = s[:end + 1]
        if tr.has_key(word): 
            return word, s[end + 1: ]
    return None, s

def get_trie_words(s):
    names = ['david', 'bob', 'karl', 'joe', 'mike']
    tr = get_trie(names)
    while s:
        word, s = get_trie_word(tr, s)
        yield word

def main(urls):
    d = Counter()
    for url in urls:
        url = "".join(a for a in url if a in string.lowercase)
        for word in get_trie_words(url):
            d[word] += 1
    return d

if __name__ == '__main__':
    urls = [
        "davidbobmike1joe",
        "mikejoe2bobkarl",
        "joemikebob",
        "bobjoe",
    ]
    print main(urls)

结果

^{pr2}$

局限性

如果你拒绝使用字典,你的算法将需要大量的计算。除此之外,不可能区分只出现一次的关键字(例如:“karl”)和糟糕的序列(例如:“e2bo”)。我的解决方案将是一个最大的努力,只有当你的网址列表包含关键字多次。在

基本思想

我假设一个单词是一系列频繁出现的字符,至少有3个字符。这就阻止了字母“o”成为最流行的单词。在

基本思路如下。在

  • 对所有n个字母序列进行计数,并选择多次出现的一次。在
  • 剪切所有属于一个较大序列的序列。在
  • 按受欢迎程度排序,你就有了一个接近解决问题的解决方案。(留给读者练习)

在代码中

import operator

sentences = ["davidbobmike1joe" , "mikejoe2bobkarl", "joemikebob", "bobjoe", "bobbyisawesome", "david", "bobbyjoe"];
dict = {}

def countWords(n):
    """Count all possible character sequences/words of length n occuring in all given sentences"""
    for sentence in sentences:
        countWordsSentence(sentence, n);

def countWordsSentence(sentence, n):
    """Count all possible character sequence/words of length n occuring in a sentence"""
    for i in range(0,len(sentence)-n+1):
        word = sentence[i:i+n]
        if word not in dict:
            dict[word] = 1;
        else:
            dict[word] = dict[word] +1;

def cropDictionary():
    """Removes all words that occur only once."""
    for key in dict.keys():
        if(dict[key]==1):
            dict.pop(key);

def removePartials(word):
    """Removes all the partial occurences of a given word from the dictionary."""
    for i in range(3,len(word)):
        for j in range(0,len(word)-i+1):
            for key in dict.keys():
               if key==word[j:j+i] and dict[key]==dict[word]:
                   dict.pop(key);

def removeAllPartials():
    """Removes all partial words in the dictionary"""
    for word in dict.keys():
        removePartials(word);

for i in range(3,max(map(lambda x: len(x), sentences))):
    countWords(i);
    cropDictionary();
    removeAllPartials();

print dict;

输出

^{pr2}$

对读者的一些挑战

  • 打印前按值对词典进行排序。(Sort a Python dictionary by value
  • 在这个例子中,“bob”出现了6次,2次是“bobby”的部分单词。确定这是否有问题,并在必要时进行修复。在
  • 把资本化考虑在内。在

相关问题 更多 >