Python 如何将文件拆分为字符
我正在制作一个python函数来查找文件中最常见的字母。但是,我无法将文件拆分为字符 以下是我目前的代码:Python 如何将文件拆分为字符,python,python-3.x,list,function,Python,Python 3.x,List,Function,我正在制作一个python函数来查找文件中最常见的字母。但是,我无法将文件拆分为字符 以下是我目前的代码: def common_letter_file(file): try: handle = open(file) except: print('Enter a valid file. Make sure the file is in the same directory as your python program') quit(
def common_letter_file(file):
try:
handle = open(file)
except:
print('Enter a valid file. Make sure the file is in the same directory as your python program')
quit()
for line in handle:
words = line.split()
for word in words:
letter_list = [char for char in word]
print(letter_list)
counts = dict()
for letter in letter_list:
counts[letter] = counts.get(letter, 0) + 1
biggest_count = None
common_letter = None
for letter,count in counts.items():
if biggest_count is None or count > biggest_count:
biggest_count = count
common_letter = letter
print('The most common letter was',common_letter,'and its count was',biggest_count)
尝试和排除以及找到频率最高的角色是有效的。但是,将文件扩展到列表中是不起作用的
请帮助,谢谢您可以将字符串拆分为单独的字符,如下所示:
>>> my_str = "foo"
>>> list(my_str)
['f', 'o', 'o']
编辑: 就KAVAY而言,这就足够了:
list(handle.read().replace("\n", ""))
并且会按文件顺序返回列表中的每个字符。我想将文件拆分为字符,而不是字符string@KAVAYSHARMA_ITSMEKAV在您的情况下,您可以使用
列表(handle.read().replace(“\n”,”)
非常感谢您的帮助answer@KAVAYSHARMA_ITSMEKAV如果答案回答了你的问题,就接受它!是的,它显示在3分钟内接受答案
line = "Ihavebeenworkingfor9hours"
line.split()
for i in line.split(): # need not to convert it to explicitly
print(i) # the better to check the lines
for j in i:
print(j)