小编cyr*_*rus的帖子

用于搜索和替换大字符串的最快Python方法

我正在寻找最快的方法来替换非常大的字符串中的大量子字符串.这是我用过的两个例子.

findall()感觉更简单,更优雅,但需要花费大量时间.

finditer()通过一个大文件,但我不确定这是正确的方法.

这是一些示例代码.请注意,我感兴趣的实际文本是一个大小约10MB的单个字符串,这两种方法有很大的不同.

import re

def findall_replace(text, reg, rep):
    for match in reg.findall(text):
        output = text.replace(match, rep)
    return output

def finditer_replace(text, reg, rep):
    cursor_pos = 0
    output = ''
    for match in reg.finditer(text):
        output += "".join([text[cursor_pos:match.start(1)], rep])
        cursor_pos = match.end(1)
    output += "".join([text[cursor_pos:]])
    return output

reg = re.compile(r'(dog)')
rep = 'cat'
text = 'dog cat dog cat dog cat'

finditer_replace(text, reg, rep)

findall_replace(text, reg, rep)
Run Code Online (Sandbox Code Playgroud)

更新为测试添加了re.sub方法:

def sub_replace(reg, rep, text):
    output = re.sub(reg, rep, text)
    return output
Run Code Online (Sandbox Code Playgroud)

结果 …

python regex

14
推荐指数
2
解决办法
1万
查看次数

查找在Python中拆分字符串的所有列表排列

我有一串字母,我想分成所有可能的组合(字母的顺序必须保持固定),这样:

s = 'monkey'
Run Code Online (Sandbox Code Playgroud)

变为:

combinations = [['m', 'onkey'], ['mo', 'nkey'], ['m', 'o', 'nkey'] ... etc]
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

python string split permutation

11
推荐指数
4
解决办法
3702
查看次数

为什么我的A*实施比洪水填充慢?

我有一个100,100个瓷砖的空白网格.起点是(0,0),目标是(99,99).瓷砖是4路连接.

我的Floodfill算法在30ms内找到最短路径,但我的A*实现速度慢了大约10倍.

注意:无论网格或布局的大小如何,A*始终比我的填充更慢(3 - 10x).因为洪水填充很简单,所以我怀疑我在A*中缺少某种优化.

这是功能.我使用Python的heapq来维护一个f排序列表.'graph'包含所有节点,目标,邻居和g/f值.

import heapq

def solve_astar(graph):

    open_q = []

    heapq.heappush(open_q, (0, graph.start_point))

    while open_q:

        current = heapq.heappop(open_q)[1]

        current.seen = True # Equivalent of being in a closed queue

        for n in current.neighbours:
            if n is graph.end_point:
                n.parent = current
                open_q = [] # Clearing the queue stops the process

            # Ignore if previously seen (ie, in the closed queue)
            if n.seen:
                continue

            # Ignore If n already has a parent and the parent is closer
            if …
Run Code Online (Sandbox Code Playgroud)

python a-star path-finding flood-fill

10
推荐指数
1
解决办法
761
查看次数

生成随机字符串的最快方法

我是Clojure和函数式编程的新手.我想以下列格式创建100,000个密钥列表:XXXXX-XXXXX-XXXXX-XXXXX-XXXXX

我做这样的事情:

(defn get-key [chunk-size, key-length] 
 (apply str 
  (flatten
   (interpose "-" 
    (partition chunk-size 
     (take key-length 
      (repeatedly #(rand-nth "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))))))))

(defn dump-keys [n, chunk-size, key-length] 
 (with-open [wrt (io/writer "keys.txt")]
  (doseq [i (range n)]
   (.write wrt (str (get-key chunk-size key-length) "\n")))))
Run Code Online (Sandbox Code Playgroud)

哪个产生

KYFL0-7YO6J-30XMV-ZIGE7-MK009
MNQZH-K7L8I-35C0K-7DS7Q-OTZWI
MVB9D-GHME9-IMGCL-YPAKX-4YZVD
... etc
Run Code Online (Sandbox Code Playgroud)

然而,它需要大约5秒,与类似的命令式算法相比,这相对较长.

什么被认为是做我想做的事情的惯用(和快速)方式?

clojure

9
推荐指数
1
解决办法
3115
查看次数

在单个LINQ查询中获取Max和Min

我有一组具有两个属性的对象,A和B.我想得到A的最小值和B的最大值.

例如

var minA = objects.Min(o => o.A);
var maxB = objects.Max(o => o.B);
Run Code Online (Sandbox Code Playgroud)

使用LINQ查询语法,有没有办法做到这一点,所以它只传递一次集合?

期望的结果将是匿名类型(例如,results.MinA = x,results.MaxB = y)

c# linq

7
推荐指数
1
解决办法
4410
查看次数

如何使用lxml和iterlinks替换链接

我是lxml的新手,我正在尝试使用iterlinks()来重写链接.

import lxml.html
html = lxml.html.document_fromstring(doc)
for element, attribute, link, pos in html.iterlinks():
    if attibute == "src":
         link = link.replace('foo', 'bar')
print lxml.html.tostring(html)
Run Code Online (Sandbox Code Playgroud)

但是,这实际上并没有取代链接.我知道我可以使用.rewrite_links,但iterlinks提供了有关每个链接的更多信息,所以我更喜欢使用它.

提前致谢.

python lxml

6
推荐指数
1
解决办法
3986
查看次数

使用单个LINQ语句将列表拆分为两个列表

我想用一个LINQ语句将列表拆分为两个列表.我现在正在这样做:

var listA = allItems.Where(item => item.IsUseful);
var listB = allItems.Except(listA);
Run Code Online (Sandbox Code Playgroud)

但是我想在查询语法中使用单个LINQ语句,它只在原始列表上迭代一次,并返回一个匿名类型,其中两个列表作为属性(例如results.ListA; results.ListB).

c# linq

2
推荐指数
2
解决办法
4395
查看次数

Python和re.compile返回不一致的结果

我试图取代的所有实例href="../directory"href="../directory/index.html".

在Python中,这个

reg = re.compile(r'<a href="../(.*?)">')
for match in re.findall(reg, input_html):
    output_html = input_html.replace(match, match+'index.html')
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

href="../personal-autonomy/index.htmlindex.htmlindex.htmlindex.html"  
href="../paternalism/index.html"  
href="../principle-beneficence/index.htmlindex.htmlindex.html"  
href="../decision-capacity/index.htmlindex.htmlindex.html" 
Run Code Online (Sandbox Code Playgroud)

知道为什么它适用于第二个链接,但其他链接不适用?

相关部分来源:

<p> 

 <a href="../personal-autonomy/">autonomy: personal</a> |
 <a href="../principle-beneficence/">beneficence, principle of</a> |
 <a href="../decision-capacity/">decision-making capacity</a> |
 <a href="../legal-obligation/">legal obligation and authority</a> |
 <a href="../paternalism/">paternalism</a> |
 <a href="../identity-personal/">personal identity</a> |
 <a href="../identity-ethics/">personal identity: and ethics</a> |
 <a href="../respect/">respect</a> |
 <a href="../well-being/">well-being</a> 

</p> 
Run Code Online (Sandbox Code Playgroud)

编辑:重复的'index.html'实际上是多个匹配的结果.(例如,href ="../ personal-autonomy/index.htmlindex.htmlindex.htmlindex.html"是因为../personal-autonomy在原始源中被找到四次).

作为一般的正则表达式问题,如何在不向所有匹配项添加额外"index.html"的情况下替换所有实例?

python regex

1
推荐指数
1
解决办法
877
查看次数

标签 统计

python ×5

c# ×2

linq ×2

regex ×2

a-star ×1

clojure ×1

flood-fill ×1

lxml ×1

path-finding ×1

permutation ×1

split ×1

string ×1