PYTHON:翻译-即时消息缩写-->;文本?
在课堂上,我们开发了IM翻译程序,该程序接收IM消息 由首字母缩略词组成,并将其转换为全文。我们使用了一本创建的词典 从一个名为缩写.txt的文件。您需要扩展代码以考虑 以下两个附加要求1)注意标点符号,2)如果首字母缩写词不在 字典,然后保留它在翻译的信息中的原样。 -使用“缩写.txt”作为字典文件名。不要询问用户文件名。 -标点符号只出现在单词的末尾。两个字母之间必须有空格 标点符号和下一个单词。需要处理的标点符号是:“,”, “,”和“!” 缩写.txt= y:为什么 r:你呢 u:你呢 l8:迟到了 哈哈:大声笑 马上回来 以下是我目前的代码:PYTHON:翻译-即时消息缩写-->;文本?,python,list,dictionary,Python,List,Dictionary,在课堂上,我们开发了IM翻译程序,该程序接收IM消息 由首字母缩略词组成,并将其转换为全文。我们使用了一本创建的词典 从一个名为缩写.txt的文件。您需要扩展代码以考虑 以下两个附加要求1)注意标点符号,2)如果首字母缩写词不在 字典,然后保留它在翻译的信息中的原样。 -使用“缩写.txt”作为字典文件名。不要询问用户文件名。 -标点符号只出现在单词的末尾。两个字母之间必须有空格 标点符号和下一个单词。需要处理的标点符号是:“,”, “,”和“!” 缩写.txt= y:为什么 r:你呢 u:你呢
# diimenhanced.py
#
def main():
infile = open("abbreviations.txt", "r")
d = {}
w = []
for line in infile:
temp = line.split(":")
d[temp[0]]=temp[1].rstrip()
w.append(temp[0])
infile.close()
im = input("Please input the instant message: ")
tim = ""
templist = im.split()
for i in templist:
if i[-1] in w:
tim = tim + ' ' + d[i]
else:
word = i[0:-1]
if word in w:
tim = tim + ' ' + d[word] + i[-1]
else:
tim = tim + i
print(tim)
main()
我一直试图让它工作,但它不断吐出相同的即时通讯,除非我把句号结束。例:BRB。-->马上回来。例如:BRB--->BRB:/明天周五到期,真的需要帮助!非常感谢。请只在介绍性python中使用im,以便您可以避免使用内置函数或复杂方法。您可以尝试将其拆分为一个列表,并在其中进行替换
def main():
infile = open("abbreviations.txt", "r")
d = {}
w = []
for line in infile:
temp = line.split(":")
d[temp[0]]=temp[1].rstrip()
# For easy punctuation marks manage add these rules
d[temp[0]+"?"] = temp[1].rstrip()+"?"
d[temp[0]+"!"] = temp[1].rstrip()+"!"
d[temp[0]+","] = temp[1].rstrip()+","
d[temp[0]+"."] = temp[1].rstrip()+"."
w.append(temp[0])
infile.close()
im = input("Please input the instant message: ")
im = im.split() # Split with space as separator
res = "" # String to store the result
for i in im: #Iterate over words
if i in d: # If the word is in our dic
res += d[i] # Add the substitution to result
else: # If no substitution needed
res += i # Add original word
res += " " # Add a space after each word
res = res.strip() # Delete extra spaces at the end
print(im)
print(res)
main()
这实际上比我的代码好一点,但当我尝试它时,循环中的每个字母都被替换了。例如:输入:lol.y r u l8用于课堂?输出:layought-oyout-loyoud。你为什么上课迟到?我用更好的方法更新了我的答案,试试看哦,我明白了,谢谢鲁本!我几乎有过类似的经历,但有点被脱衣舞卡住了。我刚才试过了。它在大多数情况下都有效,但当结尾有标点符号时,它似乎无法翻译。解决这个问题的简单方法是在你的字典中添加这样的内容,例如,对于
d[y]=why
,还要添加d[y+”?“]=why+”,d[y+!“]=why+”,d[y+!”,,d[y+,“]=why+,
,d[y+“]=why+”
非常感谢,我问我的助教,他说了一些关于带标点符号的字典的事。它起作用了。我真傻哈哈