Python 用逗号分隔字符串并删除新行字符
我有一个6行诗的文本文件 以下是我到目前为止的情况:Python 用逗号分隔字符串并删除新行字符,python,python-2.7,split,Python,Python 2.7,Split,我有一个6行诗的文本文件 以下是我到目前为止的情况: def main(): reading = read_file(); splitting = isUnique(reading); def read_file(): fp = open('BWA5.in','r'); #open file lines = fp.read(); #read file fp.close(); #close file return lines; #return li
def main():
reading = read_file();
splitting = isUnique(reading);
def read_file():
fp = open('BWA5.in','r'); #open file
lines = fp.read(); #read file
fp.close(); #close file
return lines; #return lines to main function
def isUnique(lines):
words = "";#creates blank string
for i in lines:#convert list to string
words += i;
splitWords = words.split(",");
print splitWords;
#def findUniqueChars():
#def write_file():
main();
读取文本文件并执行上述代码后,我得到的是一个包含1个元素的数组,该元素是该元素中诗歌的所有行。但是,我需要诗中的每个单词用逗号分隔,去掉新行字符,并将每个单词作为单个元素,这样我就可以在列表中搜索并单独分析每个单词
这就是它现在输出的内容,
['Hey diddle diddle\n猫和小提琴\n牛跳过了月亮\n小狗笑了\n看到这样的运动\n盘子和勺子一起跑掉了']
但我需要这样的东西,
['Hey'、'diddle'、'diddle'等](删除新行字符)此简短完整的程序可能会执行您想要的操作:
with open('BWA5.in') as fp:
words = fp.read().split()
print(words)
输出:
['Hey', 'diddle', 'diddle', 'The', 'cat', 'and', 'the', 'fiddle', 'The', 'cow', 'jumped', 'over', 'the', 'moon', 'The', 'little', 'dog', 'laughed', 'To', 'see', 'such', 'sport', 'And', 'the', 'dish', 'ran', 'away', 'with', 'the', 'spoon']
哦,天哪,请删除
代码>。在了解您如何读取文件之前,我们无法提供真正的帮助…您能分享一些示例输入和您希望获得的输出吗?在上面再次编辑一眼,似乎words+=i
将所有字母连接在一起,您应该执行words=line.strip().split(“”
以获得每个单词而不换行。