我正在学习PHP并编写了一个简单的翻译器。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Translator</title>
</head>
<body>
<form method="post" action="">
<input type="string" name="word">
<input type="submit">
</form>
<?php
if (isset($_POST["word"])) {
$word = $_POST["word"];
echo $word . " -> ";
function translate($word){
$dict = array('hello' => 'sawadee khap','thanks' => 'kap khum khap','sorry' => 'mai pen rai');
foreach ($dict as $en => $th) {
if ($word == $en) {
echo $th;
break;
}
}
}
translate($word);
} else {
echo "enter a word";
}
?>
</body>
</html>
&#13;
如何在词典中显示字符串&#39;当我输入一个不在数组中的单词?我也非常感谢有关改进代码的任何反馈或建议。
答案 0 :(得分:3)
PHP有一个函数,称为in_array
。你可以这样做:
$dict = array('hello' => 'sawadee khap','thanks' => 'kap khum khap','sorry' => 'mai pen rai');
if(!in_array($word, array_keys($dict))){
echo '"' . $word . '" not found in the dictionary.';
}else{
echo $dict[$word];
}
编辑:改进
$dict = array('hello' => 'sawadee khap','thanks' => 'kap khum khap','sorry' => 'mai pen rai');
if(!array_key_exists(strtolower($word), $dict)){
echo '"' . $word . '" not found in the dictionary.';
}else{
echo $dict[$word];
}
答案 1 :(得分:2)
更改功能代码
function translate($word){
$dict = array('hello' => 'sawadee khap','thanks' => 'kap khum khap','sorry' => 'mai pen rai');
if(array_key_exists($word, $dict)){
echo $dict[$word];
}else{
echo 'not in dictionary';
}
}
答案 2 :(得分:1)
如果在找到单词时从函数返回值,或者falsoe,否则您可以对结果进行逻辑测试以显示替代错误消息。
import traceback
import sys
from contextlib import contextmanager
@contextmanager
def output_to_file(filepath, write_mode='w'):
stdout_orig = None
stderr_orig = None
stdout_orig = sys.stdout
stderr_orig = sys.stderr
f = open(filepath, write_mode)
sys.stdout = f
sys.stderr = f
try:
yield
except:
info = sys.exc_info()
f.write('\n'.join(traceback.format_exception(*info)))
f.close()
sys.stdout = stdout_orig
sys.stderr = stderr_orig
答案 3 :(得分:1)
你可以使用array_key_exist:
$dict = array('hello' => 'sawadee khap','thanks' => 'kap khum khap','sorry' => 'mai pen rai');
if (array_key_exists($word, $dict)) {
//in dictionary
}else{
//not in dictionary
}
答案 4 :(得分:0)
请试试这个
<form method="post" action="">
<input type="string" name="word">
<input type="submit">
</form>
<?php
function translate($word) {
$dict = array('hello' => 'sawadee khap', 'thanks' => 'kap khum khap', 'sorry' => 'mai pen rai');
if (array_key_exists($word, $dict)) {
echo $dict[$word];
} else {
echo " not in dictionary";
}
}
if (isset($_POST["word"])) {
$word = $_POST["word"];
echo $word . " -> ";
translate($word);
} else {
echo "enter a word";
}
?>
答案 5 :(得分:-1)
你的top if语句缺少一个大括号。
关于你的问题,我假设你想要浏览字典,如果没有找到这个词来回应它。你可以使用一面旗帜。将它设置为for循环之前的某个内容,然后当您找到该单词时将其设置为其他内容。然后在for循环结束时检查,例如:
$found = false;
foreach ($dict as $en => $th) {
if ($word == $en) {
$found = true'
echo $th;
break;
}
}
if (!$found) echo $word;''