简体   繁体   English

AttributeError:“模块”对象没有属性“文件”

[英]AttributeError: 'module' object has no attribute 'file'

Iam working on a project where we need to find the number of words and also find no of occurences of a particular word. Iam在一个项目中工作,我们需要找到单词的数量,也没有发现特定单词的出现。

Testing.py Testing.py

import unittest
import sys
import string
import funs
from funs import *


empty_list =[]
count = 0
file_name = sys.argv[1]
search = sys.argv[2]
with open(file_name,'r') as f:
     for line in f:
         for word in line.split():
             #Effective Way
            word = word.translate(None, string.punctuation)
            word = word.lower();
            empty_list.append(word)
            count += 1


class TestMyFunction(object):
    def test_search(self):
        self.assertTrue(search_word_fun(empty_list,'kiran'),0)

if __name__ == '__main__':
    unittest.main(exit=False)

funs.py funs.py

def longest_word_fun(empty_list,longest_word):
    for each_word in empty_list:
        if (len(each_word) == len(longest_word)):
            print each_word
def search_word_fun(empty_list,search):
    print "No of times %s occurs is %d"%(search,empty_list.count(search))

def count_word_fun(count):  
    print "No of words in file is %d"%(count)

Error Log : 错误日志:

python testing.py file.txt he
Traceback (most recent call last):
  File "testing.py", line 27, in <module>
    unittest.main()
  File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__
    self.parseArgs(argv)
  File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs
    self.createTests()
  File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests
    self.module)
  File "/usr/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'file'

Here I am taking the testing file and while executing the arguments as one as normal text file and other argument is the search keyword.So it need to Test whether it is working or not by unittest. 这里我以测试文件为例,在将参数作为普通文本文件作为参数执行时,另一个参数是search关键字,因此它需要通过unittest来测试其是否正常工作。

While executing the function the error came. 执行功能时出现错误。

There is a conflict caused by unittest trying to read the command line arguments you use. 单元测试试图读取您使用的命令行参数会导致冲突。 You can solve it by reading the arguments and then deleting them before calling unittest.main(): 您可以通过读取参数并在调用unittest.main()之前将其删除来解决它:

if __name__ == '__main__':
    cmd_parameters = sys.argv[1]
    del sys.argv[1:]
    unittest.main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM