我目前正在努力解决与Python文件I / O相关的问题。我无法完成的问题是:
Write a function stats() that takes one input argument: the
name of a text file. The function should print, on the screen, the
number of lines, words, and characters in the file; your function
should open the file only once.
我还必须消除所有的惩罚以正确获取所有单词。函数应该如下打印:
>>>stats('example.txt')
line count: 3
word count: 20
character count: 98
答案 0 :(得分:1)
就你的问题而言,你可以通过以下方式实现:
fname = "inputfile.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
python有很多在线免费教程。请仔细参考。您可以找到参考书here
答案 1 :(得分:1)
请查看有关I / O here,内置函数here和常见list
操作here的Python文档。
有很多方法可以完成这项工作。快速完成后,以下内容应根据您的要求完成工作。 def GetFileCounts(in_file):
char_count = 0
word_count = 0
line_count = 0
with open(in_file) as read_file:
for line in read_file:
line_count += 1
char_count += len(line)
word_count += len(line.split(' '))
print "line count: {0}\nword count: {1}\ncharacter count: {2}".format(line_count, word_count, char_count)
函数将每行转换为let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.appController?.navigationController.popViewControllerAnimated(true)
dispatch_async(dispatch_get_main_queue()) {
tvmlContext!.evaluateScript("showTVMLView()")
}
时将消除空格。
function showTVMLView() {setTimeout(function(){_showTVMLView();}, 100);}
function _showTVMLView() {//push the next document onto the stack}
您可能希望稍微改进您的要求定义,因为有一些微妙的事情可以改变输出:
答案 2 :(得分:0)
答案 3 :(得分:0)
@nagato,我认为您使用 num_chars + = len(line)来自文件,角色和空白区域,但是感谢您的代码,我可以操作
...我
def char_freq_table():
with open('/home/.....', 'r') as f:
line = 0
word = 0
character = 0
for i in f:
line = len(list('f'))
word += len(i.split())
character = i.replace(" ", "") #lose the blank space
print "line count: ", line
print "word count: ", word
print "character count: ", len(character) # length all character
char_freq_table()