从包含不同句子的TXT文件中删除副本,但由PHP上的相同单词组成

发布于 2025-01-18 14:46:32 字数 730 浏览 0 评论 0原文

我想从TXT文件中删除重复项。现在,我用它来删除重复项:

$lines = file('input.txt');
$lines = array_unique($lines);
file_put_contents('output.txt', implode($lines));

问题是代码仅删除BEEF BBQ食谱Beef BBQ食谱之类的副本。就我而言,如果TXT文件包含以下关键字:

beef bbq recipe
beef easy recipe
beef steak recipe
bbq recipe beef
beef bbq recipe
recipe bbq beef

将以此结果返回:

beef bbq recipe
beef easy recipe
beef steak recipe
bbq recipe beef
recipe bbq beef

相反,我希望结果看起来像这样:

beef bbq recipe
beef easy recipe
beef steak recipe

所以,我想要BEEF BBQ BBQ配方BBQ bbq配方之类的案例牛肉食谱烧烤牛肉也被视为重复。有解决方案吗?谢谢

I want to remove duplicates from txt file. Now, I use this to remove duplicates:

$lines = file('input.txt');
$lines = array_unique($lines);
file_put_contents('output.txt', implode($lines));

The problem is that code only remove duplicate for a case like beef bbq recipe and beef bbq recipe only. In my case, if the txt file contains keywords like :

beef bbq recipe
beef easy recipe
beef steak recipe
bbq recipe beef
beef bbq recipe
recipe bbq beef

Will return with this result :

beef bbq recipe
beef easy recipe
beef steak recipe
bbq recipe beef
recipe bbq beef

Instead, I want the result looks like this :

beef bbq recipe
beef easy recipe
beef steak recipe

So, I want cases like beef bbq recipe, bbq recipe beef and recipe bbq beef to be considered as duplicates too. Is there a solution for this? Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ζ澈沫 2025-01-25 14:46:33

您可以使用 array_map explode sort sort 在之前,将关键字纳入相同的订单之前删除重复项:

$lines = file('input.txt');

// sort keywords in each line
$lines = array_map(function($line) {
    $keywords = explode(" ", trim($line));
    sort($keywords);
    return implode(" ", $keywords);
}, $lines);

$lines = array_unique($lines);
file_put_contents('output.txt', implode("\n", $lines));

这将迭代您的数组并按字母顺序为每行的关键字订购。之后,您可以使用 array_unique

You can use array_map, explode and sort to bring the keywords into the same order for all your lines before removing duplicates:

$lines = file('input.txt');

// sort keywords in each line
$lines = array_map(function($line) {
    $keywords = explode(" ", trim($line));
    sort($keywords);
    return implode(" ", $keywords);
}, $lines);

$lines = array_unique($lines);
file_put_contents('output.txt', implode("\n", $lines));

This will iterate your array and order the keywords for each line alphabetically. Afterwards, you can remove the duplicated lines using array_unique.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文