使用 txt 文件(包含字符串的大列表)搜索字谜
Using txt files (large lists containing strings) to search for anagrams
我正在创建一个程序来检查看似随机的字母是否实际上是连贯单词的变位词。
我正在使用来自 URL 的 .txt 文件,其中包含最常用的德语单词列表,我将其转换为数组 $dictionary
,其中每个元素都是等效的一言以蔽之。
$dictionary = file('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt');
然后我使用 explode()
:
将输入到字段中的字符串转换为数组中的单个单词
$str = $_POST["str"]; //name of the text field for the string
$words = explode(" ", $str);
然后我定义函数 is_anagram($a, $b)
,它应该检查字谜和回显 $b
,以防它们的字符匹配:
function is_anagram($a, $b) {
if (count_chars($a, 1) == count_chars($b, 1)) {
echo $b . " ";
}
}
为了比较两个数组的元素,我创建了一个 foreach
循环,其中我使用了上面提到的函数:
foreach ($words as $word) {
foreach ($dictionary as $dic) {
is_anagram($word, $dic);
}
}
如果用户编写的字符串包含一些字谜,则循环应该回显可以在 $dictionary
中找到的一些字符串。
但是,当我提交一些我知道是全等字谜的单词时,程序没有回应任何内容。
更奇怪的是,当我将 $dictionary
定义为简单数组而不是使用 .txt 文件时,例如
$dictionary = ["ahoi", "afer", "afferent"];
函数按预期运行。
我很确定 $dictionary
中存在一些错误,可能是因为 .txt 文件非常大。有谁知道如何解决这个问题?
$dictionary = file('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt');
$dictionary 是一个字符串,而不是您示例中的数组。
$tmpfile = file_get_contents('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt');
$dictionary=explode("\n",$tmpfile);
我正在创建一个程序来检查看似随机的字母是否实际上是连贯单词的变位词。
我正在使用来自 URL 的 .txt 文件,其中包含最常用的德语单词列表,我将其转换为数组 $dictionary
,其中每个元素都是等效的一言以蔽之。
$dictionary = file('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt');
然后我使用 explode()
:
$str = $_POST["str"]; //name of the text field for the string
$words = explode(" ", $str);
然后我定义函数 is_anagram($a, $b)
,它应该检查字谜和回显 $b
,以防它们的字符匹配:
function is_anagram($a, $b) {
if (count_chars($a, 1) == count_chars($b, 1)) {
echo $b . " ";
}
}
为了比较两个数组的元素,我创建了一个 foreach
循环,其中我使用了上面提到的函数:
foreach ($words as $word) {
foreach ($dictionary as $dic) {
is_anagram($word, $dic);
}
}
如果用户编写的字符串包含一些字谜,则循环应该回显可以在 $dictionary
中找到的一些字符串。
但是,当我提交一些我知道是全等字谜的单词时,程序没有回应任何内容。
更奇怪的是,当我将 $dictionary
定义为简单数组而不是使用 .txt 文件时,例如
$dictionary = ["ahoi", "afer", "afferent"];
函数按预期运行。
我很确定 $dictionary
中存在一些错误,可能是因为 .txt 文件非常大。有谁知道如何解决这个问题?
$dictionary = file('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt');
$dictionary 是一个字符串,而不是您示例中的数组。
$tmpfile = file_get_contents('https://bwinf.de/fileadmin/user_upload/BwInf/2018/37/1._Runde/Material/woerterliste.txt');
$dictionary=explode("\n",$tmpfile);