PYTHON: 翻译 - 即时消息缩写 --> 文本?
在课堂上,我们开发了一个即时消息翻译程序,它可以把包含缩写的消息转换成完整的文本。我们使用了一个字典,这个字典是从一个叫做abbreviations.txt的文件中创建的。你需要扩展这个代码,满足以下两个额外要求:1)处理标点符号,2)如果缩写不在字典里,就在翻译后的消息中保留原样。
- 使用“abbreviations.txt”作为字典文件的名称。不要询问用户文件名。
- 标点符号只出现在单词的末尾。标点符号和下一个单词之间必须有一个空格。你需要处理的标点符号有:","、"."、"?"和"!"。
abbreviations.txt 的内容是:
y:why
r:are
u:you
l8:late
lol:laught out loud
BRB:Be right back
这是我目前的代码:
# 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. ---> Be right back. 还有例子:BRB ---> BRB
:/ 明天截止,真的需要帮助!谢谢!请注意,我只是初学者,所以如果你能避免使用内置函数或复杂的方法就好了。
1 个回答
1
你可以试着把它分成一个列表,然后在里面进行替换。
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()