对于Python3,我使用新行获取字符串值
错误是当我输入d,然后输入一句话:David,yru l8 大卫,为什么你迟到了,但我需要它来报答大卫,你为什么迟到了对于Python3,我使用新行获取字符串值,python,python-3.x,Python,Python 3.x,错误是当我输入d,然后输入一句话:David,yru l8 大卫,为什么你迟到了,但我需要它来报答大卫,你为什么迟到了 def update_dictionary(fileName,dictionary): try: a = open(fileName) except IOError: print( fileName,"does not exist.") print("The dictionary has",len(dictionary),"entries.")
def update_dictionary(fileName,dictionary):
try:
a = open(fileName)
except IOError:
print( fileName,"does not exist.")
print("The dictionary has",len(dictionary),"entries.")
return dictionary
with a:
print(fileName,"loaded successfully.")
for word in a:
c,b = word.split(",")
dictionary[c] = b
print("The dictionary has",len(dictionary),"entries.")
return dictionary
def deslang(filename,dic):
x = ""
words = filename.split(" ")
for i in range(len(words)):
if words[i] in dic:
words[i] = dic[words[i]]
for i in range(len(words)-1):
x = x + words[i] + " "
x = x + words[len(words) -1]
return x
def main():
name = {}
while 1:
u_input = input("Would you like to (a)dd words to the dictionary, (d)e-slang a sentence, or (q)uit?: ")
if u_input == "q":
break
if u_input == "a":
fileName = ""
while len(fileName) == 0:
fileName = input("Enter a filename: ")
name = update_dictionary(fileName,name)
if u_input == "d":
sentence = ""
while len(sentence) == 0:
sentence = input("Enter a sentence: ")
print(deslang(sentence, name))
如果name==“main”:
main()您需要从每个字典行中删除换行符。换言之:
for word in a:
c,b = word.rstrip().split(",")
dictionary[c] = b
当您在:中为word迭代一个类似的文件时,您会得到文件中每一行的字符串,包括末尾的换行符。因此,您的词典最终充满了诸如'y':'why\n'
之类的条目,而不是'y':'why'
您需要从每个词典行中删除换行符。换言之:
for word in a:
c,b = word.rstrip().split(",")
dictionary[c] = b
当您在:
中为word迭代一个类似的文件时,您会得到文件中每一行的字符串,包括末尾的换行符。因此,您的词典最终充满了诸如'y':'why\n'
之类的条目,而不是'y':'why'
您可以通过调用
您还可以使用read()
加载不包含换行符的文件内容。您可以通过调用从word.split(“,”)中删除尾随的换行符
您还可以使用read()
加载不包含换行符的文件内容