[英]how to print only 1st argument in two arguments function?
I have a txt.file and string input as an arguments, given string input my function will print corresponding line/string from the file in a set.我有一个 txt.file 和字符串输入作为 arguments,给定字符串输入我的 function 将从一组文件中打印相应的行/字符串。 And file has one word per line.
文件每行一个单词。
def angram(s1,s2):
st = set()
if sorted(s1) == sorted(s2):
st.add(s1)
return st
angram('my.txt', 'top')
expected output: {'pot'}
but output I get {'pot','top'}
I do not want the string input in set.我不希望在集合中输入字符串。 I want only output result from file.
我只想要文件中的 output 结果。 Any way to do that??
有什么办法吗??
You need to use Python builtin functions for reading files.您需要使用 Python 内置函数来读取文件。 https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/
https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/
Given:鉴于:
car
pto
pot
Output: Output:
{'pot', 'pto'}
Code:代码:
def anagram(s1,s2):
st = set()
fh = open('my.txt')
target = sorted(s2)
while True:
line = fh.readline() # while there is line to read in the file
check = line.strip('\n') # some lines will include "\n" in index 0 - remove it
if sorted(check) == target:
st.add(check)
if not line:
break
fh.close()
st.remove(s2) # the user doesn't want the same word as the target (s2) to be included
return st
anagram('my.txt', 'top')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.