代码如下所示:
import stddraw
import sys
import stdio
#open the lexicon file
lexicon_input_file = open(sys.argv[1])
# copy the lexicon over from file
lexicon = lexicon_input_file.readlines()
#close the lexicon file
lexicon_input_file.close()
for i in range(len(lexicon)): #4000 words
# breaks down entire lexicon into each element incremented from 0,1,2,3,4,..
line_of_text = lexicon[i]
line_without_newline = line_of_text.rstrip('\n')
print(lexicon)最终结果如下所示:
['the\n', 'be\n', 'and\n', 'of\n', 'a\n', 'in\n', 'to\n', 'have\n', 'it\n'.......如何从元素的末尾去掉\n。我试过rsplit,但我不明白为什么它不起作用。我对编程真的很陌生!
发布于 2018-10-24 08:49:24
大家好,欢迎来到StackOverflow!
尝试lexicon.replace() ok,这样对于每个this线程,看起来都需要使用由'\‘或r()表示的“原始”字符。
所以它应该看起来像这样。
lexicon.replace('\\n', "")让我知道这是否有效!
发布于 2018-10-24 08:52:32
这应该会删除'\n':
lexicon = [i.strip('\n') for i in lexicon]
print(lexicon)https://stackoverflow.com/questions/52959624
复制相似问题