Я пытаюсь использовать Difflib.SequenceMatcher для вычисления сходства между двумя файлами. Эти два файла почти идентичны, за исключением того, что один содержит лишние пробелы, пустые строки, а другой - нет. Я пытаюсь использовать
s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
для этого.
Итак, вопрос в том, как написать лямбда-выражение для этого метода isjunk, чтобы метод SequenceMatcher не учитывал все пробелы, пустые строки и т. д. Я пытался использовать параметр lambda x: x == "", но результат не как здорово. Для двух очень похожих текстов соотношение очень низкое. Это очень противоречит интуиции.
Для целей тестирования вот две строки, которые вы можете использовать при тестировании:
What Motivates jwovu to do your Job Well? OK, this is an entry trying to win 0 worth of software development books despite the fact that I don‘t read
programming books. In order to win the prize you have to write an entry and
what motivatesfggmum to do your job well. Hence this post. First motivationmoney. I know, this doesn‘t sound like a great inspiration to many, and saying that money is one of the motivation factors might just blow my chances away.
As if money is a taboo in programming world. I know there are people who can‘t be motivated by money. Mme, on the other hand, am living in a real world,
with house mortgage to pay, myself to feed and bills to cover. So I can‘t really exclude money from my consideration. If I can get a large sum of money for
doing a good job, then definitely boost my morale. I won‘t care whether I am using an old workstation, or forced to share rooms or cubicle with other
people, or have to put up with an annoying boss, or whatever. The fact that at the end of the day I will walk off with a large pile of money itself is enough
for me to overcome all the obstacles, put up with all the hard feelings and hurt egos, tolerate a slow computer and even endure
А вот еще одна строка
What Motivates You to do your Job Well? OK, this is an entry trying to win 0 worth of software development books, despite the fact that I don't read programming books. In order to win the prize you have to write an entry and describes what motivates you to do your job well. Hence this post.
First motivation, money. I know, this doesn't sound like a great inspiration to many, and saying that money is one of the motivation factors might just blow my chances away. As if money is a taboo in programming world. I know there are people who can't be motivated by money. Kudos to them. Me, on the other hand, am living in a real world, with house mortgage to pay, myself to feed and bills to cover. So I can't really exclude money from my consideration.
If I can get a large sum of money for doing a good job, then thatwill definitely boost my morale. I won't care whether I am using an old workstation, or forced to share rooms or cubicle with other people, or have to put up with an annoying boss, or whatever. The fact that at the end of the day I will walk off with a large pile of money itself is enough for me to overcome all the obstacles, put up with all the hard feelings and hurt egos, tolerate a slow computer and even endure
Я выполнил указанную выше команду и установил для isjunk значение lambda x: x == "", соотношение всего 0,36.






Я не использовал Difflib.SequenceMatcher, но рассматривали ли вы возможность предварительной обработки файлов для удаления всех пустых строк и пробелов (возможно, с помощью регулярных выражений) и последующего сравнения?
Используя ваши образцы строк:
>>> s=difflib.SequenceMatcher(lambda x: x == '\n', s1, s2)
>>> s.ratio()
0.94669848846459825
Интересно, что если '' также включен как мусор:
>>> s=difflib.SequenceMatcher(lambda x: x in ' \n', s1, s2)
>>> s.ratio()
0.7653142402545744
Похоже, новые строки оказывают гораздо большее влияние, чем пробелы.
Если вы сопоставите все пробелы, сходство будет лучше:
difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()
Тем не менее, difflib не идеален для такой задачи, потому что это два почти идентичных документа, но опечатки и тому подобное создают различия для difflib, где человек не увидит многих.
Попробуйте прочитать tf-idf, Байесовская вероятность, Векторные космические модели и шинглинг
Я написал реализация tf-idf, применив его к векторному пространству и используя точечный продукт в качестве меры расстояния для классификации документов.
Учитывая приведенные выше тексты, тест действительно такой, как предлагается:
difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()
Однако, чтобы немного ускорить процесс, вы можете воспользоваться CPython методы-обертки:
difflib.SequenceMatcher(" \t\n".__contains__, doc1, doc2).ratio()
Это позволяет избежать множества вызовов функций Python.
Ссылка на вашу реализацию кажется неработающей!