- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
提前抱歉这么长的帖子
编辑--
修改自诺曼的解决方案,如果我们找到精确的解决方案,则打印并返回,否则打印所有近似匹配。对于在下面第三个 Pastebin 链接上提供的字典文件中搜索 etnse 的特定示例,目前仍仅获得 83/85 匹配。
def doMatching(file, origPattern):
entireFile = file.read()
patterns = []
startIndices = []
begin = time.time()
# get all of the patterns associated with the given phrase
for pattern in generateFuzzyPatterns(origPattern):
patterns.append(pattern)
for m in re.finditer(pattern, entireFile):
startIndices.append((m.start(), m.end(), m.group()))
# if the first pattern(exact match) is valid, then just print the results and we're done
if len(startIndices) != 0 and startIndices[0][2] == origPattern:
print("\nThere is an exact match at: [{}:{}] for {}").format(*startIndices[0])
return
print('Used {} patterns:').format(len(patterns))
for i, p in enumerate(patterns, 1):
print('- [{}] {}').format(i, p)
# list for all non-overlapping starting indices
nonOverlapping = []
# hold the last matches ending position
lastEnd = 0
# find non-overlapping matches by comparing each matches starting index to the previous matches ending index
# if the starting index > previous items ending index they aren't overlapping
for start in sorted(startIndices):
print(start)
if start[0] >= lastEnd:
# startIndicex[start][0] gets the ending index from the current matches tuple
lastEnd = start[1]
nonOverlapping.append(start)
print()
print('Found {} matches:').format(len(startIndices))
# i is the key <starting index> assigned to the value of the indices (<ending index>, <string at those indices>
for start in sorted(startIndices):
# *startIndices[i] means to unpack the tuple associated to the key i's value to be used by format as 2 inputs
# for explanation, see: http://stackoverflow.com/questions/2921847/what-does-the-star-operator-mean-in-python
print('- [{}:{}] {}').format(*start)
print()
print('Found {} non-overlapping matches:').format(len(nonOverlapping))
for ov in nonOverlapping:
print('- [{}:{}] {}').format(*ov)
end = time.time()
print(end-begin)
def generateFuzzyPatterns(origPattern):
# Escape individual symbols.
origPattern = [re.escape(c) for c in origPattern]
# Find exact matches.
pattern = ''.join(origPattern)
yield pattern
# Find matches with changes. (replace)
for i in range(len(origPattern)):
t = origPattern[:]
# replace with a wildcard for each index
t[i] = '.'
pattern = ''.join(t)
yield pattern
# Find matches with deletions. (omitted)
for i in range(len(origPattern)):
t = origPattern[:]
# remove a char for each index
t[i] = ''
pattern = ''.join(t)
yield pattern
# Find matches with insertions.
for i in range(len(origPattern) + 1):
t = origPattern[:]
# insert a wildcard between adjacent chars for each index
t.insert(i, '.')
pattern = ''.join(t)
yield pattern
# Find two adjacent characters being swapped.
for i in range(len(origPattern) - 1):
t = origPattern[:]
if t[i] != t[i + 1]:
t[i], t[i + 1] = t[i + 1], t[i]
pattern = ''.join(t)
yield pattern
原文: http://pastebin.com/bAXeYZcD - 实际功能
http://pastebin.com/YSfD00Ju - 要使用的数据,应该是 8 个“ware”匹配项,但只得到 6 个
http://pastebin.com/S9u50ig0 - 要使用的数据,应该为“etnse”获得 85 个匹配项,但只获得 77 个
我将所有原始代码留在了函数中,因为我不确定到底是什么导致了问题。
您可以在任何内容上搜索“Board:isFull()”以获得下面所述的错误。
示例:
假设您将第二个 Pastebin 命名为“someFile.txt”,该文件夹位于与 .py 文件相同的目录中名为 files 的文件夹中。
file = open('./files/someFile.txt', 'r')
doMatching(file, "ware")
或者
file = open('./files/someFile.txt', 'r')
doMatching(file, "Board:isFull()")
或者
假设您将第三个 Pastebin 命名为“dictionary.txt”,位于与 .py 文件同一目录中名为 files 的文件夹中。
file = open('./files/dictionary.txt', 'r')
doMatching(file, "etnse")
--编辑
函数参数的工作方式如下:
file 是文件的位置。
origPattern 是一个短语。
该功能基本上应该是模糊搜索。它应该采用模式并搜索文件以查找完全匹配或有 1 个字符偏差的匹配。即:1 个缺失字符、1 个额外字符、1 个替换字符或 1 个与相邻字符交换的字符。
在很大程度上它是有效的,但我遇到了一些问题。
首先,当我尝试对 origPattern 使用类似“Board:isFull()”的内容时,我得到以下结果:
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis
以上内容来自re库
我尝试过使用 re.escape() 但它没有改变任何东西。
其次,当我尝试像“Fun()”这样的其他东西时,它说它在某个索引处有一个匹配项,而该索引甚至不包含任何一个;它只是一行“*”
第三,当它找到匹配项时,它并不总是找到所有匹配项。例如,我有一个文件应该找到 85 个匹配项,但它只找到了 77 个匹配项,另一个文件有 8 个匹配项,但它只找到了 6 个。但是,它们只是按字母顺序排列的,所以这可能只是我如何处理的问题进行搜索或其他操作。
感谢任何帮助。
我也无法使用fuzzyfinder
最佳答案
我在代码中发现了一些问题:
re.escape()
似乎不起作用,因为它的结果未分配。origPattern = re.escape(origPattern)
。 re.escape('Fun()')
生成字符串 Fun\(\)
。其中的两个 \(
子字符串绝不能分开:切勿删除、替换或交换没有转义字符的 \
。Fun(\)
(删除)、Fu\n(\)
(交换)、Fun\.{0,2}\)
.Fun\)
(删除)、Fu\(n\)
(交换)、Fun.{0,2}\)
.ifindexs.__len__() != 0:
行。)您必须始终寻找它们。'.{0,2}'
的循环产生了过多的模式,例如'ware.{0,2}'
表示 ware
。除非您有意这样做,否则此模式将找到有两个插入的 wareXY
。.{0,2}
的模式无法按照描述的方式工作;它们允许一次更改和一次插入。difflib.Differ
的代码。我不明白,但我怀疑不应该有 break
语句。set
来存储索引,来自不同正则表达式的匹配仍可能重叠。\b
),尽管对于自然语言来说这是有意义的。indices.__len__() != 0
而不是 len(indices) != 0
。)我稍微重写了您的代码以解决我看到的任何问题:
def doMatching(file, origPattern):
entireFile = file.read()
patterns = []
startIndices = {}
for pattern in generateFuzzyPatterns(origPattern):
patterns.append(pattern)
startIndices.update((m.start(), (m.end(), m.group())) for m in re.finditer(pattern, entireFile))
print('Used {} patterns:'.format(len(patterns)))
for i, p in enumerate(patterns, 1):
print('- [{}] {}'.format(i, p))
nonOverlapping = []
lastEnd = 0
for start in sorted(startIndices):
if start >= lastEnd:
lastEnd = startIndices[start][0]
nonOverlapping.append(start)
print()
print('Found {} matches:'.format(len(startIndices)))
for i in sorted(startIndices):
print('- [{}:{}] {}'.format(i, *startIndices[i]))
print()
print('Found {} non-overlapping matches:'.format(len(nonOverlapping)))
for i in nonOverlapping:
print('- [{}:{}] {}'.format(i, *startIndices[i]))
def generateFuzzyPatterns(origPattern):
# Escape individual symbols.
origPattern = [re.escape(c) for c in origPattern]
# Find exact matches.
pattern = ''.join(origPattern)
yield pattern
# Find matches with changes.
for i in range(len(origPattern)):
t = origPattern[:]
t[i] = '.'
pattern = ''.join(t)
yield pattern
# Find matches with deletions.
for i in range(len(origPattern)):
t = origPattern[:]
t[i] = ''
pattern = ''.join(t)
yield pattern
# Find matches with insertions.
for i in range(len(origPattern) + 1):
t = origPattern[:]
t.insert(i, '.')
pattern = ''.join(t)
yield pattern
# Find two adjacent characters being swapped.
for i in range(len(origPattern) - 1):
t = origPattern[:]
if t[i] != t[i + 1]:
t[i], t[i + 1] = t[i + 1], t[i]
pattern = ''.join(t)
yield pattern
关于Python正则表达式与字符串匹配的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36526497/
如何使用 SPListCollection.Add(String, String, String, String, Int32, String, SPListTemplate.QuickLaunchO
我刚刚开始使用 C++ 并且对 C# 有一些经验,所以我有一些一般的编程经验。然而,似乎我马上就被击落了。我试过在谷歌上寻找,以免浪费任何人的时间,但没有结果。 int main(int argc,
这个问题已经有答案了: In Java 8 how do I transform a Map to another Map using a lambda? (8 个回答) Convert a Map>
我正在使用 node + typescript 和集成的 swagger 进行 API 调用。我 Swagger 提出以下要求 http://localhost:3033/employees/sear
我是 C++ 容器模板的新手。我收集了一些记录。每条记录都有一个唯一的名称,以及一个字段/值对列表。将按名称访问记录。字段/值对的顺序很重要。因此我设计如下: typedef string
我需要这两种方法,但j2me没有,我找到了一个replaceall();但这是 replaceall(string,string,string); 第二个方法是SringBuffer但在j2me中它没
If string is an alias of String in the .net framework为什么会发生这种情况,我应该如何解释它: type JustAString = string
我有两个列表(或字符串):一个大,另一个小。 我想检查较大的(A)是否包含小的(B)。 我的期望如下: 案例 1. B 是 A 的子集 A = [1,2,3] B = [1,2] contains(A
我有一个似乎无法解决的小问题。 这里...我有一个像这样创建的输入... var input = $(''); 如果我这样做......一切都很好 $(this).append(input); 如果我
我有以下代码片段 string[] lines = objects.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.No
这可能真的很简单,但我已经坚持了一段时间了。 我正在尝试输出一个字符串,然后输出一个带有两位小数的 double ,后跟另一个字符串,这是我的代码。 System.out.printf("成本:%.2
以下是 Cloud Firestore 列表查询中的示例之一 citiesRef.where("state", ">=", "CA").where("state", "= 字符串,我们在Stack O
我正在尝试检查一个字符串是否包含在另一个字符串中。后面的代码非常简单。我怎样才能在 jquery 中做到这一点? function deleteRow(locName, locID) { if
这个问题在这里已经有了答案: How to implement big int in C++ (14 个答案) 关闭 9 年前。 我有 2 个字符串,都只包含数字。这些数字大于 uint64_t 的
我有一个带有自定义转换器的 Dozer 映射: com.xyz.Customer com.xyz.CustomerDAO customerName
这个问题在这里已经有了答案: How do I compare strings in Java? (23 个回答) 关闭 6 年前。 我想了解字符串池的工作原理以及一个字符串等于另一个字符串的规则是
我已阅读 this问题和其他一些问题。但它们与我的问题有些无关 对于 UILabel 如果你不指定 ? 或 ! 你会得到这样的错误: @IBOutlet property has non-option
这两种方法中哪一种在理论上更快,为什么? (指向字符串的指针必须是常量。) destination[count] 和 *destination++ 之间的确切区别是什么? destination[co
This question already has answers here: Closed 11 years ago. Possible Duplicates: Is String.Format a
我有一个Stream一个文件的,现在我想将相同的单词组合成 Map这很重要,这个词在 Stream 中出现的频率. 我知道我必须使用 collect(Collectors.groupingBy(..)
我是一名优秀的程序员,十分优秀!